Michael Kupchick
Michael Kupchick

Reputation: 443

Can't return focus to the main window after showing dialog

I create dialog window in MFC using CWnd::DoModal function. The window is instantiated in CWinApp::OnIdle()

CPatientFile pf;
pf.DoModal();

When the DoModal function returns the focus is not returned to the main window. I tried to set focus manually

AfxGetMainWnd()->SetFocus();

Also tried to set the main window as foreground or active.

Generally I have touch screen, so when I close the Dialog I need to press the button on the main window to get it work.

So what is the right way to do it?

Upvotes: 2

Views: 1845

Answers (2)

Gautam Jain
Gautam Jain

Reputation: 6849

Just check the constructor of CPatientFile. It may be accepting the parent window CWnd *. Pass the main window as the parent.

Like

CPatientFile pf(this); //if this code is in main window class itelf

or

CPatientFile pf(AfxGetMainWnd());

Updated:

If you have instantiated the dialog from the main window, then the focus will automatically go back to the window when the dialog is closed. I am suspecting that you have instantiated the dialog from the app class itself (CWinApp) after creating the main window. If this is the case then the main window may not get the focus & you must create the dialog from within the main window. Or if you are creating the dialog in a separate thread.

As a work around you can use AfxGetMainWnd()->SetForegroundWindow() or AfxGetMainWnd()->SetActiveWindow(). But first I would try to find the cause of the issue & try to write better code (like suggested in above paragraph).

Upvotes: 2

Ajay
Ajay

Reputation: 18411

If you have copy-pasted, the statement is itself incorrect:

CPatientFile pf();

The next line shouldn't compile at all. Why? Because it is declaring a function named pf which returns CPatientFile.

If that is correct, may I ask if there is any multithreading involved. Is another thread creating a window? How do you check if parent windows has (not) got the focus?

Upvotes: 0

Related Questions