C# - 操作外部程式視窗

C# - 操作外部程式視窗

以下程式碼,透過 button1 控制項 Click 事件執行 ShowWindow() 方法,控制外部程式視窗狀態:包含最大化、最小化、縮到工具列、復原 等動作。

控制外部程序,請參考 Process 類別。

程式碼:

  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices; // to import Dll
  4. using System.Windows.Forms;
  5.  
  6. namespace WordTest
  7. {
  8. public partial class Form1 : Form
  9. {
  10. public Form1( )
  11. {
  12. InitializeComponent( );
  13. }
  14. [DllImport( "User32" ) ]
  15. private static extern int ShowWindow( int hwnd, int nCmdShow);
  16. private enum CommandShow : int
  17. {
  18. SW_HIDE = 0,
  19. SW_SHOWNORMAL = 1,
  20. SW_NORMAL = 1,
  21. SW_SHOWMINIMIZED = 2,
  22. SW_SHOWMAXIMIZED = 3,
  23. SW_MAXIMIZE = 3,
  24. SW_SHOWNOACTIVATE = 4,
  25. SW_SHOW = 5,
  26. SW_MINIMIZE = 6,
  27. SW_SHOWMINNOACTIVE = 7,
  28. SW_SHOWNA = 8,
  29. SW_RESTORE = 9,
  30. SW_SHOWDEFAULT = 10,
  31. SW_FORCEMINIMIZE = 11,
  32. SW_MAX = 11
  33. } ;
  34. private static void button1_Click( object sender, EventArgs e)
  35. {
  36. Process[ ] p = Process.GetProcessesByName ( "notepad" );
  37. if (p.Length > 0 )
  38. {
  39. int hwnd;
  40. hwnd = p[ 0 ].MainWindowHandle.ToInt32 ( );
  41. ShowWindow(hwnd, ( int ) CommandShow.SW_RESTORE );
  42. }
  43. }
  44. }
  45. }