【问题标题】:How can I access a dialog item in MFC from another class?如何从另一个类访问 MFC 中的对话框项?
【发布时间】:2011-12-09 21:55:39
【问题描述】:

我正在尝试从与对话框类不在同一类中的函数访问对话框项。我该怎么做?

例子:

class AnotherClass : CClas
{
  AnotherClass();
public:
  void MyFunction();
};

void AnotherClass::MyFunction() //Message overwriting, can't change parameters
{
  CClass* temp = (CClass*)GetDlgItem(IDC_ID); //Reference to dialog item IDC_ID
  temp->DoSomething(); //This gives me an assertion error
}

我知道如果它是与消息相同的对话框项,我可以使用“this”,但我想访问另一个对话框项。

感谢您的关注。

解决方案:

正如 Moo-Juice 所建议的,您可以在实例化类时简单地传递对话框。在我的情况下,我不能这样做。由于某种原因,子类化并没有那样工作。如果您在 MFC 中执行应用程序时遇到同样的问题,您可以创建一个指向 CDialog 的指针并在 OnInitDialog() 处将其传递给您的主对话框:

示例(类):

class AnotherClass : CClass
{
  AnotherClass();
public:
  void MyFunction();
  CDialog * mainDialog;
};

void AnotherClass::MyFunction() //Message overwriting, can't change parameters
{
  CClass* temp = (CClass*)mainDialog->GetDlgItem(IDC_ID); //Reference to dialog item IDC_ID
  temp->DoSomething(); //This gives me an assertion error
}

示例(OnInitDialog()):

MyMainDialog::OnInitDialog()
{
  ...
  AnotherClass obj; //Instantiate class
  obj->mainDialog = this;
  return true;
}

在此示例中,在创建对象时简单地将其作为参数传递更有意义。它只是不适合我正在做的事情。

希望对有类似问题的人有所帮助。

【问题讨论】:

    标签: mfc dialog


    【解决方案1】:

    当您实例化AnotherClass 时,将对话框类传递给它:

    class AnotherClass
    {
    private:
        CDialog& dialog_;
    
    public:
        AnotherClass(CDialog& dialog) : dialog_(dialog) { }
    
        void MyFunction();
    };
    
    
    void AnotherClass::MyFunction()
    {
        CClass* temp = (CClass*)dialog_.GetDigItem(IDC_ID);
        temp->doSOmething();
    }
    

    【讨论】:

    • 我没有完全按照你说的做,因为我在实例化类时无法通过对话框。但是你给了我一个好主意。我在 OnInitDialog() 处将指针“this”传递给我的新类中的一个指针,但我必须将我的新类中的指针公开。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多