简体   繁体   中英

How to get processes from mouse event using Intptr (USER32.dll) ???

I have a problem in last two days i want to get processes of users which he clicked. like if a user clicks Notepad my program should tell me that user clicked Notepad. Notepad is opened. And if user clicks Calculator my program also tell that user clicked Calculator. Calcultor process is runing.

For this purpose i used this code. Hook manager which gives me mouse click events but not giving me the process.

I am only getting mouse intptr event.

private static void WindowEventCallback(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
     Console.WriteLine("Event {0}", hwnd);// it is giving me mouse event 
     /*uint pid;
     GetWindowThreadProcessId(hwnd, out pid);// it gives me process id
     Process p = Process.GetProcessById((int)pid);// now here exception occured not in vs studio but when i run its exe then its gives me access violation exception
     if (!my.ContainsKey(p.MainWindowTitle.ToString()))
     {
          my.Add(p.MainWindowTitle.ToString(), p.Id.ToString());
          Console.WriteLine("\r\n");
          Console.WriteLine("Status = Running");
          Console.WriteLine("\r\n Window Title:" + p.MainWindowTitle.ToString());
          Console.WriteLine("\r\n Process Name:" + p.ProcessName.ToString());
          Console.WriteLine("\r\n Process Starting Time:" + p.StartTime.ToString());
     }*/
}

the full code is

    static void Main(string[] args)
    {
        HookManager.SubscribeToWindowEvents();

        EventLoop.Run();
    }


    public static class HookManager
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
        public static void SubscribeToWindowEvents()
        {
            if (windowEventHook == IntPtr.Zero)
            {
                windowEventHook = SetWinEventHook(
                    EVENT_SYSTEM_FOREGROUND, // eventMin
                    EVENT_SYSTEM_FOREGROUND, // eventMax
                    IntPtr.Zero,             // hmodWinEventProc
                    WindowEventCallback,     // lpfnWinEventProc
                    0,                       // idProcess
                    0,                       // idThread
                    WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);

                if (windowEventHook == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
        }

        static Dictionary<string, string> my = new Dictionary<string, string>();


        private static void WindowEventCallback(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
            Console.WriteLine("Event {0}", hwnd);
            /*uint pid;
            GetWindowThreadProcessId(hwnd, out pid);
            Process p = Process.GetProcessById((int)pid);
            if (!my.ContainsKey(p.MainWindowTitle.ToString()))
            {
                my.Add(p.MainWindowTitle.ToString(), p.Id.ToString());
                Console.WriteLine("\r\n");
                Console.WriteLine("Status = Running");
                Console.WriteLine("\r\n Window Title:" + p.MainWindowTitle.ToString());
                Console.WriteLine("\r\n Process Name:" + p.ProcessName.ToString());
                Console.WriteLine("\r\n Process Starting Time:" + p.StartTime.ToString());


            }*/
        }
    }

    private static IntPtr windowEventHook;

    private delegate void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
    [DllImport("user32.dll", SetLastError = true)]
    private static extern int UnhookWinEvent(IntPtr hWinEventHook);

    private const int WINEVENT_INCONTEXT = 4;
    private const int WINEVENT_OUTOFCONTEXT = 0;
    private const int WINEVENT_SKIPOWNPROCESS = 2;
    private const int WINEVENT_SKIPOWNTHREAD = 1;

    private const int EVENT_SYSTEM_FOREGROUND = 3;


    public static class EventLoop
    {
        public static void Run()
        {
            MSG msg;

            while (true)
            {

                if (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
                {
                    if (msg.Message == WM_QUIT)
                        break;

                    TranslateMessage(ref msg);
                    DispatchMessage(ref msg);
                }
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MSG
        {
            public IntPtr Hwnd;
            public uint Message;
            public IntPtr WParam;
            public IntPtr LParam;
            public uint Time;
        }

        const uint PM_NOREMOVE = 0;
        const uint PM_REMOVE = 1;

        const uint WM_QUIT = 0x0012;

        [DllImport("user32.dll")]
        private static extern bool PeekMessage(out MSG lpMsg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
        [DllImport("user32.dll")]
        private static extern bool TranslateMessage(ref MSG lpMsg);
        [DllImport("user32.dll")]
        private static extern IntPtr DispatchMessage(ref MSG lpMsg);
    }
}

If you want to put your logic inside the mouse click handler you can simply call GetActiveWindow to get window handle (if you dont already have it). Then you can use GetWindowThreadProcessId to get process id from window handle.

Doing this with every mouse click looks like an overkill, however. You should probably think about hooking to active window change. Check this for details: Is there Windows system event on active window changed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM