C# 影象處理: 獲取當前活動視窗控制代碼,獲取視窗大小及位置
需呼叫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;