I'm working on a C++/MFC program and I need to call a function on another window. I can get the *CWnd easily enough:
CWnd* parent_hwnd = GetParent();
Unfortunately I cannot easily access the functions on this window, though. I've read that I could get this to work if I made a member variable of the correct type, but I've had no luck with that since the class of that GetParent() window is defined in a separate project in the same solution. I'm unable to just include the .h file to cast(?) my CWnd* as the exact type. I've tried to add the other project in "Additional Include Directories" but this is a large program and when I include the other project a lot of stuff breaks. I also tried to make another .h file in the same project to define my function (sort of like what you can do for remoting) but it won't let me repeat the class names like that in C++/MFC.
When I step though the program I have no problem calling member functions like this:
But that only works at run-time, not compile time. How can I compile something that does the same as the line above? Maybe parent_hwnd->CallMemberFunc()? I was unable to find any decent documentation on that.
If the parent is a specific window you want to access some function, you need a pointer or a reference of the specific type. You do not need any member variable. Local variable is good enough
You would have to cast CWnd return type to the parent’s class type. Function has to be public.
Example of casting:
CSomeWndClass* pParent = (CSomeWndClass*)GetParent()
CSomeWndClass* pParent = static_cast<CSomeWndClass*>(GetParent());
Now you can use pParent to access public members of CSomeWndClass.
There are only 10 types of people in the world: Those who understand binary and those who do not.
In my opinion, developers should never rely on window hierarchy to pass data and/or access business logic.
Sure it all starts out innocently enough (with a child window only called by one parent window), but then it snowballs when new functionality is required and the child window gets called by multiple parents - then the code becomes nasty because the child needs to determine which parent type called it and what 'fixups' are needed to access the desired method.
One answer to all this is to use the doc/view architecture and call GetActiveDocument( ).
This allows you to access the business logic with the CDocument derived class. If the business logic is currently in your view, then pull it out of there and put it into the document ('cuz it doesn't belong in the view).
If you aren't using the doc/view architecture, you can still create a psuedo doc/view architecture, by creating a 'document' class (which contains data, business logic and methods) and then create an instance of this class within the CWinApp derived class. Then you can access the CWinApp derived class from anywhere in your app using AfxGetWinApp( ). From there you can access your 'document' class.