gpt4 book ai didi

wpf - WPF 中处理系统关闭

转载 作者:行者123 更新时间:2023-12-02 04:03:58 26 4
gpt4 key购买 nike

如何在 WPF 中重写 WndProc?当我的窗口关闭时,我尝试检查我正在使用的文件是否被修改,如果是,我必须提示用户“你想保存更改吗?”消息,然后关闭正在使用的文件和窗口。但是,当我的窗口仍然打开时,我无法处理用户重新启动/关闭/注销的情况。由于我正在使用 WPF 进行开发,所以我无法覆盖 WndProc。我也尝试过使用 this sample MSDN code .这就是我所做的 私有(private)无效loadForm(对象发送者,RoatedEventArgs 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",但是当我单击“是/否”时没有任何反应,我的应用程序不会关闭。如果我尝试使用关闭按钮再次关闭它,我会收到错误消息?为什么会这样呢?是因为胡克吗??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();
}
}

最佳答案

为什么不使用 Application.SessionEnding事件?这似乎是为了做你想做的事情而设计的,你不需要直接处理 Windows 消息。

如果想取消关闭,您可以在 SessionEndingCancelEventArgs 上将 Cancel 设置为 true。

关于wpf - WPF 中处理系统关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1141134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com