C# 启动时将程序放入系统托盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/283632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:35:12  来源:igfitidea点击:

Put a program in the system tray at startup

c#.netvb.net

提问by thomasb

I followed the commonly-linked tip for reducing an application to the system tray : http://www.developer.com/net/csharp/article.php/3336751Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.

我遵循了将应用程序减少到系统托盘的通用链接提示:http: //www.developer.com/net/csharp/article.php/3336751现在它可以工作了,但仍然存在一个问题:我的应用程序显示什么时候开始;我希望它直接在系统托盘中启动。我试图将它最小化并隐藏在 Load 事件中,但它什么也没做。

Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.

编辑:我可以按照海报的建议修改快捷方式属性,但我宁愿使用代码:我无法完全控制安装该软件的每台计算机。

I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.

我不想从系统托盘之外的任何地方完全删除它,我只是希望它开始最小化。

Any ideas ?

有任何想法吗 ?

Thanks

谢谢

采纳答案by Sunlight

In your main program you probably have a line of the form:

在你的主程序中,你可能有这样一行:

Application.Run(new Form1());

This will force the form to be shown. You will need to create the form but notpass it to Application.Run:

这将强制显示表单。您将需要创建表单但不要将其传递给Application.Run

Form1 form = new Form1();
Application.Run();

Note that the program will now not terminate until you call Application.ExitThread(). It's best to do this from a handler for the FormClosedevent.

请注意,该程序现在不会终止,直到您调用Application.ExitThread(). 最好从FormClosed事件的处理程序中执行此操作。

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    Application.ExitThread();
}

回答by Marc Gravell

If you are using a NotifyIcon, try changing ShowInTaskbar to false.

如果您使用的是NotifyIcon,请尝试将 ShowInTaskbar 更改为 false。

To remove it from the Alt+Tab screen, try changing your window border style; I believe some of the tool-window styles don't appear...

要将其从 Alt+Tab 屏幕中删除,请尝试更改窗口边框样式;我相信一些工具窗口样式不会出现......

something like:

就像是:

using System;
using System.Windows.Forms;
class MyForm : Form
{
    NotifyIcon sysTray;

    MyForm()
    {
        sysTray = new NotifyIcon();
        sysTray.Icon = System.Drawing.SystemIcons.Asterisk;
        sysTray.Visible = true;
        sysTray.Text = "Hi there";
        sysTray.MouseClick += delegate { MessageBox.Show("Boo!"); };

        ShowInTaskbar = false;
        FormBorderStyle = FormBorderStyle.SizableToolWindow;
        Opacity = 0;
        WindowState = FormWindowState.Minimized;
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}

If it still appears in the Alt+Tab, you can change the window styles through p/invoke (a bit hackier):

如果它仍然出现在 Alt+Tab 中,您可以通过 p/invoke 更改窗口样式(有点 hackier):

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    IntPtr handle = this.Handle;
    int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);
    SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);
}
private const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr window, int index, int value);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr window, int index);

回答by xan

As a bit of a cludge, you could configure the shortcut that launches your app to "run minimised"? That might give you what you need!

有点麻烦,您可以将启动应用程序的快捷方式配置为“最小化运行”?这可能会给你你需要的东西!

Like so: (image just an example from google)...

像这样:(图片只是谷歌的一个例子)...

Run Minimized
(source: unixwiz.net)

运行最小化
(来源:unixwiz.net

回答by lubos hasko

this is how you do it

这就是你的方式

static class Program
{
    [STAThread]
    static void Main()
    {
        NotifyIcon icon = new NotifyIcon();
        icon.Icon = System.Drawing.SystemIcons.Application;
        icon.Click += delegate { MessageBox.Show("Bye!"); icon.Visible = false; Application.Exit(); };
        icon.Visible = true;
        Application.Run();
    }
}

回答by rjrapson

Since this was tagged with vb.net, here's what I did in a Windows Service and Controller app I just finished, Add a code module to the project, Setup the NotifyIcon and it's associated Context menu in Sub Main(), and then set the application's Startup Object to the Sub Main() instead of the Form.

由于这是用 vb.net 标记的,这是我在刚刚完成的 Windows 服务和控制器应用程序中所做的,向项目添加代码模块,在 Sub Main() 中设置 NotifyIcon 及其关联的上下文菜单,然后设置应用程序的启动对象到 Sub Main() 而不是 Form。

Public mobNotifyIcon As NotifyIcon
Public WithEvents mobContextMenu As ContextMenu

Public Sub Main()

    mobContextMenu = New ContextMenu
    SetupMenu()
    mobNotifyIcon = New NotifyIcon()
    With mobNotifyIcon
        .Icon = My.Resources.NotifyIcon
        .ContextMenu = mobContextMenu
        .BalloonTipText = String.Concat("Monitor the EDS Transfer Service", vbCrLf, "Right click icon for menu")
        .BalloonTipIcon = ToolTipIcon.Info
        .BalloonTipTitle = "EDS Transfer Monitor"
        .Text = "EDS Transfer Service Monitor"
        AddHandler .MouseClick, AddressOf showBalloon
        .Visible = True
    End With
    Application.Run()
End Sub

Private Sub SetupMenu()
    With mobContextMenu

        .MenuItems.Add(New MenuItem("Configure", New EventHandler(AddressOf Config)))
        .MenuItems.Add("-")
        .MenuItems.Add(New MenuItem("Start", New EventHandler(AddressOf StartService)))
        .MenuItems.Add(New MenuItem("Stop", New EventHandler(AddressOf StopService)))
        .MenuItems.Add("-")
        .MenuItems.Add(New MenuItem("Exit", New EventHandler(AddressOf ExitController)))
    End With
    GetServiceStatus()
End Sub

In the Config(), I create an instance of my form and display it.

在 Config() 中,我创建了表单的一个实例并显示它。

Private Sub Config(ByVal sender As Object, ByVal e As EventArgs)
    Using cs As New ConfigureService
        cs.Show()
    End Using

End Sub

回答by rjrapson

Here you go:

干得好:

Create 2 classes, 1 which inherits from ApplicationContext. The other only contains a Main routine. I've made an example that has a form and a notifyicon that when double clicked brings up the form and back again.

创建 2 个类,其中 1 个类继承自 ApplicationContext。另一个只包含一个 Main 例程。我做了一个例子,它有一个表单和一个通知图标,当双击时会弹出表单并再次返回。

Remember to set "Sub Main" as your startup object in My Project settings and point to a real *.ico file instead of f:\TP.ico .. :)

请记住在“我的项目”设置中将“Sub Main”设置为您的启动对象,并指向一个真正的 *.ico 文件而不是 f:\TP.ico .. :)

Code should of course be stuffed with proper error handling code.

代码当然应该填充适当的错误处理代码。

Class1:

类1:

Imports System.threading 
Imports System.Runtime.InteropServices 
Imports System.Windows.Forms


Public Class Class1

    <System.STAThread()> _
        Public Shared Sub Main()

        Try
            System.Windows.Forms.Application.EnableVisualStyles()
            System.Windows.Forms.Application.DoEvents()
            System.Windows.Forms.Application.Run(New Class2)
        Catch invEx As Exception

            Application.Exit()

        End Try


    End Sub 'Main End Class 

Class2:

类2:

Imports System.Windows.Forms  
Imports System.drawing

Public Class Class2
    Inherits System.Windows.Forms.ApplicationContext

    Private WithEvents f As New System.Windows.Forms.Form
    Private WithEvents nf As New System.Windows.Forms.NotifyIcon

    Public Sub New()

        f.Size = New Drawing.Size(50, 50)
        f.StartPosition = FormStartPosition.CenterScreen
        f.WindowState = Windows.Forms.FormWindowState.Minimized
        f.ShowInTaskbar = False
        nf.Visible = True
        nf.Icon = New Icon("f:\TP.ico")
    End Sub


    Private Sub nf_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles nf.DoubleClick
        If f.WindowState <> Windows.Forms.FormWindowState.Minimized Then
            f.WindowState = Windows.Forms.FormWindowState.Minimized
            f.Hide()
        Else
            f.WindowState = Windows.Forms.FormWindowState.Normal
            f.Show()
        End If
    End Sub

    Private Sub f_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles f.FormClosed
        Application.Exit()
    End Sub  End Class

回答by rjrapson

This shows you how to control startup as minimized or normal as well as much more with NotifyIcon.

这将向您展示如何使用 NotifyIcon 以最小化或正常以及更多方式控制启动。

More here: http://code.msdn.microsoft.com/TheNotifyIconExample

更多信息:http: //code.msdn.microsoft.com/TheNotifyIconExample