簡體   English   中英

當最小化到系統托盤中時,WPF窗口在以下情況下不會響應來自其他實例的PostMessage的消息:

[英]When minimized into the system tray, a WPF Window does not respond to message from PostMessage from the other instance when

我正在執行一個任務,當同一應用程序的第二個實例啟動時,從系統托盤還原和最大化窗口。

當第二個實例啟動並且無法獲取互斥鎖時。 它調用以下代碼來表示第一個實例顯示自己:

public static void ShowFirstInstance()

  {
     WinApi.PostMessage(
        (IntPtr)WinApi.HWND_BROADCAST, 
        WM_SHOWFIRSTINSTANCE, 
        IntPtr.Zero, 
        IntPtr.Zero);
  }

使用以下方法注冊該消息:

public static readonly int WM_SHOWFIRSTINSTANCE =
         WinApi.RegisterWindowMessage("WM_SHOWFIRSTINSTANCE|{0}", 250);

我在窗口后面的代碼中包含以下內容,以捕獲消息並顯示該窗口:

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
      {
         if (msg == SingleInstance.WM_SHOWFIRSTINSTANCE)
         {
             WinApi.ShowToFront(hwnd);
         }

         return IntPtr.Zero;
      }

當我測試出來。 每當第一個實例藏在系統托盤中時,該消息就永遠不會捕獲。 我想念什么嗎?

謝謝,

這是我過去的做法:

App.xaml.cs:

private static readonly Mutex Mutex = new Mutex(true, "{" + YourGuidHere + "}");

//return true if other instance is open, allowing for UI cleanup/suspension while shutdown() is completed
private bool EnforceSingleInstance()
{
    //try...catch provides safety for if the other instance is closed during Mutex wait
    try
    {
        if (!Mutex.WaitOne(TimeSpan.Zero, true))
        {
            var currentProcess = Process.GetCurrentProcess();

            var runningProcess =
                Process.GetProcesses().Where(
                    p =>
                    p.Id != currentProcess.Id &&
                    p.ProcessName.Equals(currentProcess.ProcessName, StringComparison.Ordinal)).FirstOrDefault();

            if (runningProcess != null)
            {
                WindowFunctions.RestoreWindow(runningProcess.MainWindowHandle);

                Shutdown();
                return true;
            }
        }

        Mutex.ReleaseMutex();
    }
    catch (AbandonedMutexException ex)
    {
        //do nothing, other instance was closed so we may continue
    }
    return false;
}

WindowFunctions:

//for enum values, see http://www.pinvoke.net/default.aspx/Enums.WindowsMessages
public enum WM : uint
{
    ...
    SYSCOMMAND = 0x0112,
    ...
}

//for message explanation, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
private const int SC_RESTORE = 0xF120;

public static void RestoreWindow(IntPtr hWnd)
{
    if (hWnd.Equals(0))
        return;

    SendMessage(hWnd,
                (uint)WM.SYSCOMMAND,
                SC_RESTORE,
                0);
}

[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd,
                                        uint msg,
                                        uint wParam,
                                        uint lParam);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM