简体   繁体   English

如何在 ac#.net winforms 应用程序中编写 alt+tab 关闭按钮

[英]how to program the alt+tab close button in a c#.net winforms application

I have this winform app that tracks battery life, if I close the app during an "alt+tab" (like in the pic below) it closes the app completely.我有这个跟踪电池寿命的 winform 应用程序,如果我在“alt+tab”期间关闭应用程序(如下图所示),它会完全关闭应用程序。

在此处输入图像描述

I want to program the close button (if this is possible) to minimize the app to the system tray instead of closing it completely.我想对关闭按钮(如果可能的话)进行编程,以将应用程序最小化到系统托盘,而不是完全关闭它。

I have not seen any similar solutions for this, all I see is disabling the alt+tab on a winforms app.我还没有看到任何类似的解决方案,我所看到的只是禁用 winforms 应用程序上的 alt+tab。

I want to do this because if I close the app the battery percentage wont be monitored anymore, I just want to know if this is possible though.我想这样做是因为如果我关闭应用程序,电池百分比将不再受到监控,我只是想知道这是否可行。

In order to minimize to system tray first add NotifyIcon on your form from Toolbox.为了最小化到系统托盘,首先从工具箱中在您的表单上添加 NotifyIcon。 And then add this code accordingly.然后相应地添加此代码。

private System.Windows.Forms.ContextMenu notifyMenu;
private System.Windows.Forms.MenuItem notifyMenuItemClose;
public static bool close = false;

public ApplicationWindow()
{
    InitializeComponent();
}

private void ApplicationWindow_Load(object sender, EventArgs e)
{
    this.notifyMenu = new System.Windows.Forms.ContextMenu();
    this.notifyMenuItemClose = new System.Windows.Forms.MenuItem();
    this.notifyMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.notifyMenuItemClose });
    this.notifyMenuItemClose.Index = 0;
    this.notifyMenuItemClose.Text = "Exit";
    this.notifyMenuItemClose.Click += new System.EventHandler(this.notifyMenuItemClose_Click);
    this.notifyAppIcon.ContextMenu = this.notifyMenu;

}

private void notifyMenuItemClose_Click(object sender, EventArgs e)
{
    close = true;
    this.Close();
}

private void ApplicationWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (close)
    {
        e.Cancel = false;
    }
    else
    {
        WindowState = FormWindowState.Minimized;
        e.Cancel = true;
    }
}

private void notifyAppIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if (e.Button==MouseButtons.Left)
    {
        this.Show();
        WindowState = FormWindowState.Normal;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM