How to access a dialog item in MFC from another class

dialogmfc

I'm trying to access a dialog item from a function that is not in the same class as the dialog class. How can I do that?

Example:

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
}

I know I can use "this" if it is the same dialog item than the message, but I want to access another dialog item.

Thanks for your attention.

Solution:

As suggested by Moo-Juice, you can simply pass the dialog when you instantiate the class. In my case, I couldn't do that. For some reason subclassing didn't work that way. If you face the same issue when doing an application in MFC , you can create a pointer to a CDialog and pass it your main dialog at OnInitDialog():

Example (Class):

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
}

Example (OnInitDialog()):

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

In this example simply passing it as a parameter when creating the object makes more sense. It just didn't work with me for what I was doing.

Hope it helps anyone with a similar question.

Best Answer

When you instantiate AnotherClass, pass it the dialog class:

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();
}