Windows 窗体应用程序无法正常关闭

本文关键字:常关闭 窗体 应用程序 Windows | 更新日期: 2023-09-27 18:37:21

关闭窗口表单应用程序时遇到问题。我需要知道,如果我按表单上的 X 按钮并且只是单击以关闭计算机,它是否总是private void Form1_FormClosing(object sender, FormClosingEventArgs e)调用?

任何人 这个时间表格都没有像往常一样关闭。我总是有屏幕按结束 现在

我在表单关闭时连接到数据库,并将一些记录复制到另一个数据库。这也许是问题所在吗?表单正在快速关闭,sql 命令无法完成?

我试过Enviroment.Exit(0)Application.Exit()。似乎没有任何正常工作。

如何让它完成所有 sql 然后退出?

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //close database connection
            if (Con.State == ConnectionState.Open)
                Con.Close();
            info.Dispose();
            //last check for local database
            try
            {
               // database queries and so on....
            }
            catch (Exception ex)
            {
                writeToLogFile(ex.Message);
            }
            // exit
            Environment.Exit(0);
        }

Windows 窗体应用程序无法正常关闭

更新(基于您的最后一条评论):

private const int WM_QUERYENDSESSION = 0x11;
private const int WM_CANCELMODE = 0x1f;
private bool shutdownRequested = false;
...
protected override void WndProc(ref Message ex)
{
    if (ex.Msg == WM_QUERYENDSESSION)
    {
        Message MyMsg = new Message();
        MyMsg.Msg = WM_CANCELMODE;
        base.WndProc(ref MyMsg);
        this.shutdownRequested = true;
    }
    else
    {
        base.WndProc(ex);
    }
}
...
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Visible = false; // optional
    this.ShowInTaskbar = false; // optional
    Task db = Task.Factory.StartNew(() => DBUpdate();
    Task.WaitAll(db); // you can have more tasks like the one above
    if (this.shutdownRequested)
        Process.Start("shutdown.exe","-s");
}
private void DBUpdate()
{
    // write your db code here
}

我相信这会奏效。

任何人 这个时间表格都没有像往常一样关闭。我总是有屏幕按结束 现在

您是说您希望应用程序在计算机重新启动或关闭时自动关闭吗?

如果是这样,只需将事件挂接到 Microsoft.Win32.SystemEvents.SessionEnding 事件。

Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(SystemEvents_SessionEnding);
void SystemEvents_SessionEnding(object sender, Microsoft.Win32.SessionEndingEventArgs e)
    {
        // Run your application shut down code here...
    }