Link to home
Start Free TrialLog in
Avatar of jerm
jerm

asked on

Window handle

How do you retrieve the handle of the main window in an SDI application?  I need the HWND value for various procedures, but not sure if I have it correctly.  Example prefered.

Thanks
Avatar of jtwine100697
jtwine100697
Flag of United States of America image

  Assuming you are using MFC, try AfxGetMainWnd().  That will return a CWnd*, from which you can obtain the HWND.

-=- James.
ASKER CERTIFIED SOLUTION
Avatar of HoJu
HoJu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vsinha
vsinha

I think a simpler solution would be:

hwndMain = (HWND) GetWindow(hwnd, GWL_OWNER);

I am however not an expert (currently) in this topic, so try it and correct me if I am wrong.
sorry about the previous comment, it should have been:

I think a simpler solution would be:

hwndMain = GetParent(hwnd);

I am however not an expert (currently) in this topic, so try it and correct me if I am wrong.
  "vsinha", you are assuming that the immediate parent will be the main window...

   That is not always the case. :P

-=- James.
Jtwine, I guess this is not my question, but it would be very helpful if you could give me an example where my soln. won't work and yours will. Also could you explain why?

  If you are in, say, a dialog box, or in a custom control that is implemented in a window (or in the view of an MFC Doc/View MDI application), the parent of the "current" window might not be the "main window" of the application.  (Note the question reads "various procedures".  That could mean various windows.)

   You (We) need more details on the specifics of where "jerm" wants to obtain the main window from.  If using MFC, AfxGetMainWnd() works...  Anywhere.

-=- James.

jtwine, thanks. If you are not using MFC would this function work:

HWND GetMainWnd(HWND hwnd)
{
   while (GetParent(hwnd) != NULL)
      hwnd = GetParent(hwnd);
   
   return hwnd;
}

[written, based on the fact that the parent of the main window is NULL]

Also didn't HoJu`s soln. have the same drawback as mine.
  Yes, the function (loop) will work as expected.  (That, BTW, is similar to how MFC delegates control [updates] for Context Menus!)

   And yes, the Answer posted by "Hoju" has the same problem.  That is why I try to contain myself and post suggestions before wasting time with possibly incorrect answers! :)

-=- James.