开发者

How to detect differentiate external wm_close vs internally triggered by form.close()

开发者 https://www.devze.com 2023-03-24 19:50 出处:网络
This is a C# app that sits in the tray as a notifyicon and does its stuff until someone right clicks it and selects close (menu option) or it gets a wm_close from an external app or by the operating s

This is a C# app that sits in the tray as a notifyicon and does its stuff until someone right clicks it and selects close (menu option) or it gets a wm_close from an external app or by the operating system say during a reboot.

protected override void WndProc(ref Message m)
{
   case  Win32.WmClose:
  //recvd message to shutdown
   Program.Log.InfoFormat("Shutdown received at {0}", DateTime.Now);
   CleanUp();
   this.Close(); //this is the main form
   break;

   //other case statements here开发者_运维百科
}

//somewhere else on menu exit of notify icon
 private void toolStripMenuItemExit_Click(object sender, EventArgs e)
 {
        Program.Log.InfoFormat("Manual EXIT at {0}", DateTime.Now);
        CleanUp();
        this.Close(); //this is the main form
 }

The this.close() triggers another WM_CLOSE sending the app in a tailspin. What is the correct way to handle this situation ? thank you


Handle form Closing event. and whenever you want to exit just call Close();, and make any other operation rely on closing inside the closing event instead of handling it at WndProc and toolStripMenuItemExit_Click, so:

private void OnFormCloseing(object sender, FormClosingEventArgs e)
{
    string reason = string.Empty;
    switch (e.CloseReason)
    {
        case CloseReason.UserClosing:
            reason = "Manual EXIT";
            break;

        case CloseReason.WindowsShutDown:
            reason = "Shutdown received";
            break;
    }
    Program.Log.InfoFormat(reason + " at {0}", DateTime.Now);
    CleanUp();
}

private void toolStripMenuItemExit_Click(object sender, EventArgs e)
{
    this.Close(); //this is the main form
}

More members of CloseReason here.


Remove the CleanUp() call from both toolStripMenuItemExit_Click and WndProc.

Add a FormClosing() event handler in the main window form (assuming you have one). Again, assuming you have a main form window, why do you have a WndProc at all?

The CleanUp() will only be done once, but you will still have two log messages, though both are accurate.

0

精彩评论

暂无评论...
验证码 换一张
取 消