Original address: http://www.mgenware.com/blog/?p=339
The ShowDialog method of windows in WPF does not provide parameters for setting the owner, and developers need to set the Owner property of the window before ShowDialog, which is why many times you may forget to set the owner, Show the dialog box directly. The dialog box appears to be fine, but when the user switches the form on the taskbar or switches to the program, the dialog box appears behind the main form, and the main form is not point! If the main form can overwrite the entire dialog box (which is usually the case), then the user will not be able to manipulate the entire program at this point, which is discussed in another article.
Writing a helper type automatically sets the owner and then calls the ShowDialog method, and of course the automatically set owner is the current form of Windows, which gets the handle of the current form through the GetForegroundWindow API. It is then converted into a WPF window object.
classdialoghelper{//get the Window object from handle StaticWindow Getwindowfromhwnd (IntPtr hwnd) {return(Window) Hwndsource.fromhwnd (HWND). RootVisual; } //GetForegroundWindow API[DllImport ("user32.dll")] Static externIntPtr GetForegroundWindow (); //call GetForegroundWindow and call Getwindowfromhwnd StaticWindow Gettopwindow () {varhwnd =GetForegroundWindow (); if(hwnd = =NULL) return NULL; returnGetwindowfromhwnd (HWND); } //Displays the dialog box and automatically sets the owner Public Static voidShowDialog (Window win) {win. Owner=Gettopwindow (); Win. ShowInTaskbar=false; Win. ShowDialog (); }}
Finally, the direct call to ShowDialog static method is possible!
Dialoghelper.showdialog (new MainWindow ());
"Go" WPF: Automatically set owner's ShowDialog for MVVM