最大化已经运行的windowc#

最大化已经运行的windowc#,c#,C#,下面是工作正常的代码。 如果应用程序已在运行,则其最大化/恢复应用程序或在前端显示应用程序。。工作完美,但现在的问题是当窗口被最小化到系统托盘 this.showInTaskbar = false; this.WindowState = System.Windows.WindowState.Minimized; 它不是还原应用程序,我应该怎么做?要使其也从系统托盘恢复/最大化 [DllImport("user32.dll", EntryPoint = "SetForegroundW

下面是工作正常的代码。 如果应用程序已在运行,则其最大化/恢复应用程序或在前端显示应用程序。。工作完美,但现在的问题是当窗口被最小化到系统托盘

 this.showInTaskbar = false;
 this.WindowState = System.Windows.WindowState.Minimized;
它不是还原应用程序,我应该怎么做?要使其也从系统托盘恢复/最大化

    [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

    private const int SW_SHOWMAXIMIZED = 1;


    public NewDesign(){
             InitializeComponent();

     if (!EnsureSingleInstance()){
                 System.Environment.Exit(0);
     }
   }

    static bool EnsureSingleInstance()
    {
        Process currentProcess = Process.GetCurrentProcess();

        var runningProcess = (from process in Process.GetProcesses()
                              where
                                process.Id != currentProcess.Id &&
                                process.ProcessName.Equals(
                                  currentProcess.ProcessName,
                                  StringComparison.Ordinal)
                              select process).FirstOrDefault();

        if (runningProcess != null)
        {
            ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
            SetForegroundWindow(runningProcess.MainWindowHandle);


            return false;
        }

        return true;
    }

简单的方法是从C#项目中引用Microsoft.VisualBasic运行时,从中派生应用程序类(即使在C#中也可以这样做),在其上设置
IsSingleInstance=true
,并处理
StartupNextInstance
事件。在某些情况下不起作用,但适用于常见情况


一种更为惯用的C#方法可以在一个落入时间之沙中,必须使用回溯机器挖掘的地方找到:使用命名管道与已经运行的实例进行对话。甚至还有一些代码可以在那里使用。

代码很脆弱,这取决于MainWindowHandle的风险。将ShowInTaskbar属性设置为false会导致重新创建窗口,从而使情况变得更糟。所以不要这样做,改用这个.Hide()。@HansPassant你的建议很好,但是我应该如何显示隐藏的窗口呢?在上面的方法中,showWindow中没有参数(MainHandle,uuuuuuuuuuuuuuuuuuuuuuuuuuuu);如果你想不出来,就别用它。Jeffrey给了你很好的建议,避免重新实现框架已经支持的东西。