【问题标题】:Ensure single instance of a WPF application : Difficulty restoring the already running application to the foreground确保 WPF 应用程序的单个实例:难以将已经运行的应用程序恢复到前台
【发布时间】:2012-03-28 09:06:11
【问题描述】:

意图:运行 WPF 应用程序的单个实例。当一个新实例启动时,应该将已经运行的实例设置为前台。

虽然我已经实现了大部分,但当已经运行的应用程序位于通知托盘中时,我遇到了问题。代码运行没有错误,但无法恢复窗口并将其设置为前台。 代码片段 (c#):

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

[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

var currentProcess = Process.GetCurrentProcess();

string processName = currentProcess.ProcessName;
Process[] instances = Process.GetProcessesByName(processName);

if (instances.Length > 1)
{
    foreach(var instance in instances)
    {
        if (!currentProcess.Id.Equals(instance.Id))
        {
            IntPtr hWnd = instance.MainWindowHandle;

            if (IsIconic(hWnd))
                ShowWindow(hWnd, SW_RESTORE);

            SetForegroundWindow(hWnd);
        }
    }
    currentProcess.Kill();
}

谁能指出我做错了什么。再次重申,它适用于已经运行的窗口处于最大化状态但事后诸葛亮的情况。当已经运行的窗口最小化到通知托盘时,它会失败。

谢谢

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您是否验证过,当系统托盘中已运行的进程已在运行时,您的代码会执行ShowWindow?我在问,因为我不认为 IsIconic 是正确使用的函数:documentation 声明它“确定指定的窗口是否最小化”。如果进程在系统托盘中,它没有被最小化,它是隐藏的。

    我认为你应该改用IsWindowVisible

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多