Ejemplo n.º 1
0
        /// <summary>
        /// 切换窗口时的回调函数(同一进程下的线程窗口切换也会触发)
        /// </summary>
        /// <param name="hWinEventHook"></param>
        /// <param name="eventType"></param>
        /// <param name="hwnd"></param>
        /// <param name="idObject"></param>
        /// <param name="idChlid"></param>
        /// <param name="dwEventThread"></param>
        /// <param name="dwmsEventTime"></param>
        public void WindowBaseEvent(IntPtr hWinEventHook, Int32 eventType, IntPtr hwnd, long idObject, long idChlid, Int32 dwEventThread, Int32 dwmsEventTime)
        {
            // 获取窗口句柄所代表的进程id, 该函数返回值为窗口代表线程id
            UInt16 threadId = DLLInvoke.GetWindowThreadProcessId(hwnd, out processId);

            // 过滤同一进程下切换线程的情况
            if (preProcessId == processId)
            {
                return;
            }

            preProcessId = processId;

            Process process = null;

            // 过滤掉已终止的进程
            try
            {
                process = Process.GetProcessById((int)processId);
            } catch (ArgumentException e)
            {
                Console.WriteLine("id为[" + processId + "]的进程未运行");
                return;
            } catch (InvalidOperationException e)
            {
                MessageBox.Show("未知错误");
            }

            String modulePath = null;

            // 过滤某些系统应用无法获取到主模块路径的情况
            try
            {
                modulePath = process.MainModule.FileName;
            }
            catch (Exception e)
            {
                Console.WriteLine("无权限访问当前应用的文件路径 [" + process.ProcessName + "]");
                Console.WriteLine(e.Message);
                //MessageBox.Show("无权限访问当前应用的文件路径 [" + process.ProcessName + "]");
                return;
            }
            Console.WriteLine("PID: " + processId);
            Console.WriteLine("进程主模块名: " + process.MainModule.ModuleName);
            Console.WriteLine("进程主模块路径: " + process.MainModule.FileName);

            windowSwitchEvent.Invoke(process);
        }
Ejemplo n.º 2
0
        public static int GetForegroundWindowProcessId()
        {
            uint   pid;
            IntPtr windowHandle = DLLInvoke.GetForegroundWindow();

            try
            {
                DLLInvoke.GetWindowThreadProcessId(windowHandle, out pid);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                //MessageBox.Show(e.Message);
                return(-1);
            }
            return((int)pid);
        }