簡體   English   中英

SetWindowsHookEx由C#生成的另一個進程始終返回0 IntPtr

[英]SetWindowsHookEx another process made by C# always return 0 IntPtr

我試圖將鼠標單擊事件鈎到由C#制成的Windows應用程序中。

這是我的代碼;

private const int WH_MOUSE = 7;

[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

private static IntPtr SetHook(LowLevelMouseProc proc)
{
    IntPtr hWnd = IntPtr.Zero;
    uint processId = 0;
    uint threadID = 0;
    string moduleName   = string.Empty;
    Process[] localAll = Process.GetProcesses();
    string toFindModule  ="windowsformsapplication1.exe";
    foreach (Process p in localAll)
    {
        if (p.MainWindowHandle != IntPtr.Zero)
        {
            ProcessModule pm = GetModule(p);
            if (pm != null && p.MainModule.FileName.ToLower().IndexOf(toFindModule) > -1)
            {
                hWnd = p.MainWindowHandle;
                threadID = GetWindowThreadProcessId(hWnd, out processId);
                break;
            }
        }
    }

    IntPtr ret = SetWindowsHookEx(WH_MOUSE, proc, IntPtr.Zero, threadID);

    return ret;
}

我已經保證WindowsFormsApplication1.exe的線程ID。

但是, IntPtr ret = SetWindowsHookEx(WH_MOUSE, proc, IntPtr.Zero, threadID); 總是返回0;

因此,我啟用了掛鈎鼠標單擊事件。

我的代碼有問題嗎?

我什至嘗試了calc.exe ,但也沒有運氣。

編輯

而且我非常確定我捕獲了目標Winform的正確線程ID。

在此處輸入圖片說明

您不能在C#中使用全局WH_MOUSE鈎子,也不能在不同進程中為線程使用特定於線程的WH_MOUSE鈎子。 這需要一個非托管的DLL。

從托管代碼中,您需要使用WH_MOUSE_LL (低級鼠標掛鈎)。 如果確實需要WH_MOUSE則需要用本機代碼編寫鈎子,以便可以將DLL注入目標進程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM