[C#][WinForm]如何取得當前視窗

  • 8907
  • 0
  • C#
  • 2009-12-07

[C#][WinForm]如何取得當前視窗

網友問題,自己簡單實做記錄。

引用user32.dll API即可達到該需求。

參考GetForegroundWindow Function


[DllImport("user32.dll")]
 private  static extern Int32 GetForegroundWindow();
[DllImport("user32.dll")]
 private static extern Int32 GetWindowText(Int32 hWnd, StringBuilder lpsb, Int32 count);

private void Form1_Load(object sender, EventArgs e)
        {
            Timer mytimer = new Timer();
            mytimer.Tick +=new EventHandler(mytimer_Tick);
            mytimer.Start();

        }

private void mytimer_Tick(object sender, EventArgs e)
        {
            GetCurrentWindow();//取得活動視窗
        }

private void GetCurrentWindow()
        {           
            Int32 handle = 0;
            StringBuilder sb = new StringBuilder(256);          
            handle = GetForegroundWindow();
            if (GetWindowText(handle, sb, sb.Capacity) > 0)
            {
                label1.Text = "視窗標題:" + sb.ToString();
            } 
        }

image image image