你好 yemx21,
我找到了一个方法能让你只调用Show方法就能够打开一个模态窗体, 在你的父窗体中首先要通过 API EnableWindow 函数来使父窗体Disable, 然后show子窗体,在子窗体中通过调用API
EnableWindow(handle, true);
SetForegroundWindow(handle);
来使得子窗体成为模态,最后在子窗体关闭的时候别忘了取消这些设置:
MainWindow.cs:
public partial class MainWindow : Window
{
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hwnd, int index);
[DllImport("user32.dll")]
static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
IntPtr handle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;
Window1 dialog = new Window1();
dialog.Owner = this;
WindowInteropHelper helper = new WindowInteropHelper(dialog);
EnableWindow(handle, false);
dialog.Show();
}
}
Window1.cs:
public partial class Window1 : Window
{
[DllImport("user32.dll")]
static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Window1()
{
InitializeComponent();
IntPtr handle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;
EnableWindow(handle, true);
SetForegroundWindow(handle);
this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);
}
void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.Closing -= new System.ComponentModel.CancelEventHandler(Window1_Closing);
IntPtr handle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;
IntPtr ownerhandle = (new System.Windows.Interop.WindowInteropHelper(this.Owner)).Handle;
EnableWindow(handle, false);
EnableWindow(ownerhandle, true);
}
}
这里可以下载实例:http://cid-51b2fdd068799d15.office.live.com/self.aspx/.Public/Samples%5E_2010/20101223%5E_ShowAModalWindow.zip
Sincerely,
Bob Bao [MSFT]
MSDN Community Support |
Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
