C# 通过pid获取hwnd / 通过pid查找hwnd

hwnd = Process.GetProcessById(99999).MainWindowHandle;

C#中,如果你想要通过句柄Handle获取Windows桌面或特定窗口的截图,可以借助WinAPI函数结合GDI+(Graphics Device Interface)来实现。以下是一个基本步骤: 1. **获取句柄**:首先,你需要获取到你要截图窗口的句柄,这通常是通过`GetWindowThreadProcessId()`、`FindWindow()`或其他相关的Windows API函数。 2. **转换到设备上下文(DC)**:然后将句柄转换为Device Context(HDC),这对于屏幕捕捉至关重要。 3. **创建位图**:使用`CreateCompatibleBitmap()`创建一个与屏幕分辨率相同的位图。 4. **复制屏幕到位图**:使用`BitBlt()`或`CopyBits()`函数将屏幕复制到刚才创建的位图上。 5. **释放资源**:最后记得释放之前创建的所有GDI对象,包括位图和DC。 下面是一个简单的示例: ```csharp using System.Runtime.InteropServices; using System.Drawing; // ...假设已经得到了窗口的句柄hwnd [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left; public int Top; public int Right; public int Bottom; } [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hWnd); [DllImport("gdi32.dll", SetLastError = true)] static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int width, int height); [DllImport("gdi32.dll")] static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int width, int height, IntPtr hdcSrc, int xSrc, int ySrc, uint dwRop); // ... RECT rect = new RECT(); GetWindowRect(hwnd, out rect); IntPtr hMemDC = GetDC(hwnd); IntPtr hBitmap = CreateCompatibleBitmap(hMemDC, rect.Right - rect.Left, rect.Bottom - rect.Top); BitBlt(hMemDC, 0, 0, rect.Width, rect.Height, hBitmap, 0, 0, Win32.BITMAP_SCOPY); Bitmap bitmap = new Bitmap(rect.Width, rect.Height, hBitmap); Graphics g = Graphics.FromImage(bitmap); g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); g.Dispose(); // 现在你可以对bitmap做进一步处理,比如保存图片或者显示 // 释放资源 DeleteObject(hBitmap); ReleaseDC(hwnd, hMemDC); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值