基于C#實(shí)現(xiàn)獲取Windows所有窗口句柄
寫(xiě)在前面
在做錄屏或截屏操作時(shí),需要獲取當(dāng)前正在運(yùn)行中的桌面程序句柄,在網(wǎng)上查找資源的的時(shí)候,發(fā)現(xiàn)了一個(gè)工具類還不錯(cuò),這邊做個(gè)驗(yàn)證記錄。
參考代碼
public class WindowApi
{
//尋找目標(biāo)進(jìn)程窗口
[DllImport("USER32.DLL")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
//設(shè)置進(jìn)程窗口到最前
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
#region GetWindowCapture的dll引用
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(
IntPtr hdc // handle to DC
);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(
IntPtr hdc, // handle to DC
int nWidth, // width of bitmap, in pixels
int nHeight // height of bitmap, in pixels
);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(
IntPtr hdc, // handle to DC
IntPtr hgdiobj // handle to object
);
[DllImport("gdi32.dll")]
private static extern int DeleteDC(
IntPtr hdc // handle to DC
);
[DllImport("user32.dll")]
private static extern bool PrintWindow(
IntPtr hwnd, // Window to copy,Handle to the window that will be copied.
IntPtr hdcBlt, // HDC to print into,Handle to the device context.
UInt32 nFlags // Optional flags,Specifies the drawing options. It can be one of the following values.
);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowDC(
IntPtr hwnd
);
#endregion
/// <summary>
/// 根據(jù)句柄獲取截圖
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
public static Bitmap GetWindowCapture(IntPtr hWnd)
{
IntPtr hscrdc = GetWindowDC(hWnd);
Rectangle windowRect = new Rectangle();
GetWindowRect(hWnd, ref windowRect);
int width = Math.Abs(windowRect.X - windowRect.Width);
int height = Math.Abs(windowRect.Y - windowRect.Height);
IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
IntPtr hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, hbitmap);
PrintWindow(hWnd, hmemdc, 0);
Bitmap bmp = Image.FromHbitmap(hbitmap);
DeleteDC(hscrdc);//刪除用過(guò)的對(duì)象
DeleteDC(hmemdc);//刪除用過(guò)的對(duì)象
return bmp;
}
/// <summary>
/// 根據(jù)句柄獲取截圖路徑
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
public static string GetCapturePath(IntPtr hWnd)
{
string path = string.Empty;
string dicPath = AppDomain.CurrentDomain.BaseDirectory + "Intercept";
if (!Directory.Exists(dicPath))
{
Directory.CreateDirectory(dicPath);
}
using (Bitmap bitmap = GetWindowCapture(hWnd))
{
path = dicPath + "\\" + Guid.NewGuid().ToString().Replace("-", "") + ".png";
bitmap.Save(path);
}
return path;
}
private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
//用來(lái)遍歷所有窗口
[DllImport("user32.dll")]
private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
//獲取窗口Text
[DllImport("user32.dll")]
private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
//獲取窗口類名
[DllImport("user32.dll")]
private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
//自定義一個(gè)結(jié)構(gòu),用來(lái)保存句柄信息
public struct WindowInfo
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
public static WindowInfo[] GetAllDesktopWindows()
{
//用來(lái)保存窗口對(duì)象 列表
List<WindowInfo> wndList = new List<WindowInfo>();
//enum all desktop windows
EnumWindows(delegate (IntPtr hWnd, int lParam)
{
WindowInfo wnd = new WindowInfo();
StringBuilder sb = new StringBuilder(256);
//get hwnd
wnd.hWnd = hWnd;
//get window name
GetWindowTextW(hWnd, sb, sb.Capacity);
wnd.szWindowName = sb.ToString();
//get window class
GetClassNameW(hWnd, sb, sb.Capacity);
wnd.szClassName = sb.ToString();
//add it into list
wndList.Add(wnd);
return true;
}, 0);
return wndList.ToArray();
}
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 釋放內(nèi)存
/// </summary>
public async static Task ClearMemory()
{
//獲得當(dāng)前工作進(jìn)程
Process proc = Process.GetCurrentProcess();
long usedMemory = proc.PrivateMemorySize64;
if (usedMemory > 1024 * 1024 * 10)
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
}
await Task.Delay(10);
}
}
}調(diào)用結(jié)果

調(diào)用示意:
var programList = WindowApi.GetAllDesktopWindows().Where(x => !string.IsNullOrEmpty(x.szWindowName)).ToList();
listBoxWindows.DataSource = programList.Select(x => x.szWindowName).ToList();
以上就是基于C#實(shí)現(xiàn)獲取Windows所有窗口句柄的詳細(xì)內(nèi)容,更多關(guān)于C#獲取Windows窗口句柄的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#開(kāi)發(fā)之微信小程序發(fā)送模板消息功能
這篇文章主要介紹了C#開(kāi)發(fā)之微信小程序發(fā)送模板消息功能,需要的朋友可以參考下2017-09-09
基于C#實(shí)現(xiàn)簡(jiǎn)單離線注冊(cè)碼生成與驗(yàn)證
本文使用RSA非對(duì)稱加密和Base64簡(jiǎn)單地實(shí)現(xiàn)離線注冊(cè)碼的生成與驗(yàn)證功能。感興趣的朋友跟著小編一起學(xué)習(xí)吧2015-09-09
C#在驗(yàn)證文件共享模式下實(shí)現(xiàn)多線程文件寫(xiě)入
這篇文章主要為大家詳細(xì)介紹了C#在驗(yàn)證文件共享模式下實(shí)現(xiàn)多線程文件寫(xiě)入的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2024-01-01

