Search code examples
c#hookmouse-hook

how to Install global mouse Hook for certain UI like "desktop"


the code so far installs a hook to detect the mouse activity but what i want is either to filter the activity for certain UI or to detect where the clicks has occurred (on which hwnd ) exactly 'Desktop' is there a way ?

this is the code i've used it's from Microsoft website here : How to set a Windows hook in Visual C# .NET

EDIT : i found that he code provided by is not global so for global hook check link in the answer the answer ,,


Solution

  • First about the hook i found that it's not global and i found open-source global hook Here so whenever the mouse click occurs an event will fire and there i run simple callback code that checks if the desktop is the active control

    [DllImport("user32.dll")]
    static extern int GetForegroundWindow();
    
    [DllImport("user32.dll")]
    static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount);
    
    public void GetActiveWindow() {
    const int maxChars = 256;
    int handle = 0;
    StringBuilder className = new StringBuilder(maxChars);
    
    handle = GetForegroundWindow();
    
    if (GetClassName(handle, className, maxChars) > 0) {
        string cName = className.ToString();
        if (cName == "Progman" || cName == "WorkerW") {
            // desktop is active
        } else {
            // desktop is not active
        }
    }
    

    }

    DONE!

    special thanks to Micky Duncaand and AJKenny84