C#獲得windows工作列視窗控制代碼及一些操作(放大、縮小、關閉、隱藏……)
需呼叫API函式
需在開頭引入名稱空間
using System.Runtime.InteropServices;
1、通過視窗名字查詢
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lp1, string lp2);
示例:
IntPtr hWnd = FindWindow(null, "abc");
2、對視窗進行在工作列隱藏和開啟操作
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
public static extern IntPtr ShowWindow(IntPtr hWnd, int _value);
0 隱藏視窗到後臺
1 正常大小顯示視窗
3、獲取當前焦點視窗的控制代碼
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
使用方法 : IntPtr myPtr=GetForegroundWindow();
4、獲取到該視窗控制代碼後,可以對該視窗進行操作
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
使用例項: ShowWindow(myPtr, 0);
0 關閉視窗
1 正常大小顯示視窗
2 最小化視窗
3 最大化視窗
5、獲取視窗大小,及螢幕座標
[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 = rect.Right - rect.Left; //視窗的寬度
int height = rect.Bottom - rect.Top; //視窗的高度