"Go" WPF: Automatically set owner's ShowDialog for MVVM

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.