C#擷取進程的主視窗控制代碼的實現方法

來源:互聯網
上載者:User

通過調用Win32 API實現。

複製代碼 代碼如下:public class User32API
{
private static Hashtable processWnd = null;

public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);

static User32API()
{
if (processWnd == null)
{
processWnd = new Hashtable();
}
}

[DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);

[DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
public static extern IntPtr GetParent(IntPtr hWnd);

[DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

[DllImport("user32.dll", EntryPoint = "IsWindow")]
public static extern bool IsWindow(IntPtr hWnd);

[DllImport("kernel32.dll", EntryPoint = "SetLastError")]
public static extern void SetLastError(uint dwErrCode);

public static IntPtr GetCurrentWindowHandle()
{
IntPtr ptrWnd = IntPtr.Zero;
uint uiPid = (uint)Process.GetCurrentProcess().Id; // 當前進程 ID
object objWnd = processWnd[uiPid];

if (objWnd != null)
{
ptrWnd = (IntPtr)objWnd;
if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 從緩衝中擷取控制代碼
{
return ptrWnd;
}
else
{
ptrWnd = IntPtr.Zero;
}
}

bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
// 枚舉視窗返回 false 並且沒有錯誤號碼時表明擷取成功
if (!bResult && Marshal.GetLastWin32Error() == 0)
{
objWnd = processWnd[uiPid];
if (objWnd != null)
{
ptrWnd = (IntPtr)objWnd;
}
}

return ptrWnd;
}

private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
{
uint uiPid = 0;

if (GetParent(hwnd) == IntPtr.Zero)
{
GetWindowThreadProcessId(hwnd, ref uiPid);
if (uiPid == lParam) // 找到進程對應的主視窗控制代碼
{
processWnd[uiPid] = hwnd; // 把控制代碼緩衝起來
SetLastError(0); // 設定無錯誤
return false; // 返回 false 以終止枚舉視窗
}
}

return true;
}
}

調用User32API.GetCurrentWindowHandle()即可返回當前進程的主視窗控制代碼,如果擷取失敗則返回IntPtr.Zero。

--EOF--

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.