標籤:
需調用API函數
需在開頭引入命名空間 using System.Runtime.InteropServices;
擷取當前視窗控制代碼:GetForegroundWindow()
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetForegroundWindow();
傳回值類型是IntPtr,即為當前獲得焦點視窗的控制代碼
使用方法 : IntPtr myPtr=GetForegroundWindow();
擷取到該視窗控制代碼後,可以對該視窗進行操作.比如,關閉該視窗或在該視窗隱藏後,使其顯示
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
其中ShowWindow(IntPtr hwnd, int nCmdShow);
nCmdShow的含義
0 關閉視窗
1 正常大小顯示視窗
2 已最小化的視窗
3 已最大化的視窗
使用執行個體: ShowWindow(myPtr, 0);
擷取視窗大小及位置:需要調用方法GetWindowRect(IntPtr hWnd, ref RECT lpRect)
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; //最左座標 public int Top; //最上座標 public int Right; //最右座標 public int Bottom; //最下座標 }
樣本:
InPtr awin = GetForegroundWindow(); //擷取當前視窗控制代碼 RECT rect = new RECT(); GetWindowRect(awin, ref rect); int width = rc.Right - rc.Left; //視窗的寬度 int height = rc.Bottom - rc.Top; //視窗的高度 int x = rc.Left; int y = rc.Top;
API抓屏