如何在 WPF 中覆盖 WndProc?当我的窗口关闭时,我会尝试检查我正在使用的文件是否被修改,如果是,我必须提示用户“你想保存更改吗?” 消息,然后关闭正在使用的文件和窗口。但是,当我的窗口仍然打开时,我无法处理用户重新启动/关闭/注销的情况。我无法覆盖 WndProc,因为我正在使用 WPF 进行开发。我也尝试过使用这个示例 MSDN 代码。这就是我所做的 private void loadedForm(object sender, RoutedEventArgs e) {
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_QUERYENDSESION.)
{
OnWindowClose(this, new CancelEventArgs())
handled = true;
shutdown = true;
}
return IntPtr.Zero;
}
private void OnWindowClose(object sender, CancelEvetArgs e)
{
if (modified)
{
//show message box
//if result is yes/no
e.cancel = false;
//if cancel
e.cancel = true;
}
}
在 XAML 文件上,我也使用了,Closing = "OnWindowClose"
但是当我单击是/否时没有任何反应,我的应用程序没有关闭。如果我尝试使用关闭按钮再次关闭它,我会收到错误消息?为什么会这样?是因为Hook吗??在 WPF 中这个等价物是什么?
private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg==WM_QUERYENDSESSION)
{
systemShutdown = true;
}
// If this is WM_QUERYENDSESSION, the closing event should be
// raised in the base WndProc.
base.WndProc(m);
} //WndProc
private void Form1_Closing(
System.Object sender,
System.ComponentModel.CancelEventArgs e)
{
if (systemShutdown)
// Reset the variable because the user might cancel the
// shutdown.
{
systemShutdown = false;
if (DialogResult.Yes==MessageBox.Show("My application",
"Do you want to save your work before logging off?",
MessageBoxButtons.YesNo))
{
SaveFile();
e.Cancel = false;
}
else{
e.Cancel = true;
}
CloseFile();
}
}