WPF 精修篇 窗体唯一(Single) 显示在最前

原文: WPF 精修篇 窗体唯一(Single) 显示在最前

只运行一个窗体 并在一次点击时 显示到最前

发现用

SetForegroundWindow 并不是稳定的有效 

最后使用 SetWindowPos

贴码了


  
  
  1. public const int HWND_TOPMOST = -1;
  2. public const int HWND_NOTOPMOST = -2;
  3. protected override void OnStartup(StartupEventArgs e)
  4. {
  5. bool isNewInstance;
  6. base.OnStartup(e);
  7. Mutex mutex = new Mutex( true, "Single", out isNewInstance);
  8. if (isNewInstance != true)
  9. {
  10. IntPtr intPtr = FindWindowW( null, "Single");
  11. if (intPtr != IntPtr.Zero)
  12. {
  13. SetWindowPos(intPtr, HWND_TOPMOST, 0, 0, 0, 0, 1 | 2);
  14. SetWindowPos(intPtr, HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
  15. SetForegroundWindow(intPtr);
  16. }
  17. Shutdown();
  18. }
  19. }
  20. [ DllImport("User32", CharSet = CharSet.Unicode)]
  21. static extern IntPtr FindWindowW(String lpClassName, String lpWindowName);
  22. [ DllImport("User32", CharSet = CharSet.Unicode)]
  23. static extern Boolean SetForegroundWindow(IntPtr hWnd);
  24. [ DllImport("user32.dll", CharSet = CharSet.Auto)]
  25. private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);
  26. [ DllImport("user32.dll")]
  27. public static extern IntPtr SetFocus(IntPtr hWnd);

代码:

https://download.csdn.net/download/q465162770/12003540

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12075430.html