示例#1
0
        public static int GetAForegroundApplicationProcessId()
        {
            IntPtr foregroundWindow = InteropWindow.GetForegroundWindow();

            if (foregroundWindow == IntPtr.Zero)
            {
                return(0);
            }
            uint ProcessId             = 0;
            int  windowThreadProcessId = (int)InteropWindow.GetWindowThreadProcessId(foregroundWindow, ref ProcessId);

            return((int)ProcessId);
        }
示例#2
0
        public static bool ForceSetForegroundWindow(IntPtr h)
        {
            if (h == IntPtr.Zero)
            {
                return(false);
            }
            IntPtr foregroundWindow = InteropWindow.GetForegroundWindow();

            if (foregroundWindow == IntPtr.Zero)
            {
                return(InteropWindow.SetForegroundWindow(h));
            }
            if (h == foregroundWindow)
            {
                return(true);
            }
            uint ProcessId             = 0;
            uint windowThreadProcessId = InteropWindow.GetWindowThreadProcessId(foregroundWindow, ref ProcessId);
            uint currentThreadId       = InteropWindow.GetCurrentThreadId();

            if ((int)currentThreadId == (int)windowThreadProcessId)
            {
                return(InteropWindow.SetForegroundWindow(h));
            }
            if (windowThreadProcessId != 0U)
            {
                if (!InteropWindow.AttachThreadInput(currentThreadId, windowThreadProcessId, true))
                {
                    return(false);
                }
                if (!InteropWindow.SetForegroundWindow(h))
                {
                    InteropWindow.AttachThreadInput(currentThreadId, windowThreadProcessId, false);
                    return(false);
                }
                InteropWindow.AttachThreadInput(currentThreadId, windowThreadProcessId, false);
            }
            return(true);
        }