如何在窗口启动时将WPF应用程序移动到最小化托盘?使用C#。

7

我已经使用Windows Installer创建了我的应用程序的安装程序。

现在我想在Windows启动时启动应用程序,并将其移动到系统最小化托盘,因为我不希望在Windows启动时显示GUI(视图)。

我已经在Google上搜索,发现可以使用注册表键,但这对我来说还不够,因为我还想将应用程序移动到系统最小化托盘并运行。

我的目的是,当用户启动系统时,他/她每次启动应用程序时都不会感到烦恼。

有没有人有答案? 谢谢..

3个回答

4

你还需要设置此属性才能将其从任务栏中移除

ShowInTaskbar= false;

4

在你的应用程序中,为FrameworkElement.Loaded事件添加一个事件处理程序。在该处理程序中,添加以下代码:

WindowState = WindowState.Minimized;

这将使应用程序在启动时最小化。

要在计算机启动时启动应用程序,您需要将程序添加到Windows计划任务中,并设置其在启动时运行。您可以在MSDN的计划任务页面了解更多信息。


2
我想让它在计算机启动时最小化,而不是每次用户单击图标时都最小化。 - user1584245

2
也许这个答案有点晚,但我仍然想写下来帮助那些还没有找到解决方案的人。
首先,您需要添加一个函数,在系统启动时自动启动时将应用程序最小化到托盘中。
  1. 在您的App.xaml文件中,将原始的StartupUri=...更改为如下所示的Startup="App_Startup"App_Startup是您的函数名称,可以更改。
<Application x:Class="Yours.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="App_Startup">

在你的App.xaml.cs文件中,添加下面的函数:
public partial class App : Application
{    
    private void App_Startup(object sender, StartupEventArgs e)
    {
        // Process command line args
        var isAutoStart = false;
        for (int i = 0; i != e.Args.Length; ++i)
        {
            if (e.Args[i] == "/AutoStart")
            {
                isAutoStart = true;
            }
        }

        // Create main application window, starting minimized if specified
        MainWindow mainWindow = new MainWindow();
        if (isAutoStart)
        {
            mainWindow.WindowState = WindowState.Minimized;
        }
        mainWindow.OnAutoStart();
    }
}

在你的MainWindow.xaml.cs文件中,添加以下函数:
public void OnAutoStart()
{
    if (WindowState == WindowState.Minimized)
    {
        //Must have this line to prevent the window start locatioon not being in center.
        WindowState = WindowState.Normal;
        Hide();
        //Show your tray icon code below
    }
    else
    {
        Show();
    }
}

然后,您应该将您的应用程序设置成系统启动。

  1. 如果您有一个开关来决定是否将您的应用程序设置为系统启动,则可以将以下函数添加为您的开关状态更改事件函数。
private void SwitchAutoStart_OnToggled(object sender, RoutedEventArgs e)
{
    const string path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
    var key = Registry.CurrentUser.OpenSubKey(path, true);
    if (key == null) return;
    if (SwitchAutoStart.IsOn)
    {
        key.SetValue("Your app name", System.Reflection.Assembly.GetExecutingAssembly().Location + " /AutoStart");
    }
    else
    {
        key.DeleteValue("Your app name", false);
    }
}

如果你想让应用程序在Windows启动时自动为所有用户启动,只需将第四行替换为

RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true);

^_^


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接