WPF: automatically sets the Owner's ShowDialog for MVVM and showdialogmvvm.

Source: Internet
Author: User

[Switch] WPF: automatically sets the Owner's ShowDialog for MVVM and showdialogmvvm.

Original address: http://www.mgenware.com/blog? P = 339

The ShowDialog method of Windows in WPF does not provide parameters for setting the Owner. developers need to set the Owner attribute of the Window before ShowDialog. Because of this, you may forget to set the Owner many times, the dialog box is displayed directly. The displayed dialog box does not appear to be correct. However, when you switch the form on the taskbar or switch to the program, the dialog box is displayed after the main form, and the main form cannot be clicked at this time! If the main form can overwrite the entire dialog box (normally this is the case), then the user will not be able to operate the entire program. This issue has been carefully discussed in another article.

If a secondary type is set, the Owner is automatically set and then the ShowDialog method is called. Of course, the automatically set Owner is the current Windows form. You can use the GetForegroundWindow API to obtain the handle of the current form, then convert it to the Window object of WPF.

Class DialogHelper {// obtain the Window object static Window GetWindowFromHwnd (IntPtr hwnd) {return (Window) HwndSource from Handle. fromHwnd (hwnd ). rootVisual;} // GetForegroundWindow API [DllImport ("user32.dll")] static extern IntPtr GetForegroundWindow (); // call GetForegroundWindow and then call GetWindowFromHwnd static Window GetTopWindow () {var hwnd = GetForegroundWindow (); if (hwnd = null) return null; return GetWindowFromHwnd (hwnd );} // display the dialog box and automatically set the Owner public static void ShowDialog (Window win) {win. owner = GetTopWindow (); win. showInTaskbar = false; win. showDialog ();}}

Finally, call the ShowDialog static method!

DialogHelper.ShowDialog(new MainWindow());

 

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.