code_junkie

How do I focus a foreign window?

Nov 13th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
  2. System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
  3. foreach (System.Diagnostics.Process p in myProcesses)
  4. {
  5. if (p.ProcessName == me.ProcessName)
  6. if (p.Id != me.Id)
  7. {
  8. //if already running, abort this copy.
  9. return;
  10. }
  11. }
  12. //launch the application.
  13. //...
  14.  
  15. [System.Runtime.InteropServices.DllImport("user32.dll")]
  16. public static extern bool SetForegroundWindow(IntPtr hWnd);
  17.  
  18. //...
  19. if (p.Id != me.Id)
  20. {
  21. //if already running, focus it, and then abort this copy.
  22. SetForegroundWindow(p.MainWindowHandle);
  23. return;
  24. }
  25. //...
  26.  
  27. [System.Runtime.InteropServices.DllImport("user32.dll")]
  28. public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
  29.  
  30. [STAThread]
  31. static void Main()
  32. {
  33. System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
  34. System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
  35. foreach (System.Diagnostics.Process p in myProcesses)
  36. {
  37. if (p.Id != me.Id)
  38. {
  39. SwitchToThisWindow(p.MainWindowHandle, true);
  40. return;
  41. }
  42. }
  43. //now go ahead and start our application ;-)
  44.  
  45. Process.GetProcessesByName(me.ProcessName)
  46.  
  47. private const SW_SHOWNORMAL = 1
  48.  
  49. <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
  50. Private Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As integer) As Boolean
  51. End Function
  52.  
  53. <DllImport("user32.dll", SetLastError:=True)> _
  54. Private Function SetForegroundWindow(ByVal hwnd As IntPtr) As Boolean
  55. End Function
  56.  
  57. Sub SetForeground()
  58. Dim processes As Process() = Process.GetProcessesByName("myprocess")
  59.  
  60. For Each p as Process in processes
  61. ShowWindow(p.MainWindowHandle, SW_SHOWNORMAL)
  62. SetForegroundWindow(p.MainWindowHandle)
  63. Next
  64. End Sub
Add Comment
Please, Sign In to add comment