How to set focus back to form after opening up a process (Notepad)?

前端 未结 5 1996
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 12:01

I open up a notepad from my program using Process.Start() but the new opened notepad covers the screen. But I do want my application to maintain its focus.

5条回答
  •  半阙折子戏
    2020-12-06 12:40

    Windows prevents apps from shoving their window into the user's face, you are seeing this at work. The exact rules when an app may steal the focus are documented in the MSDN docs for AllowSetForegroundWindow().

    A back-door around this restriction is the AttachThreadInput() function. This code worked well, I did take a shortcut on finding the thread ID for the thread that owns the foreground window. Good enough for Notepad, possibly not for other apps. Do beware that Raymond Chen does not approve of this kind of hack.

        private void button1_Click(object sender, EventArgs e) {
            var prc = Process.Start("notepad.exe");
            prc.WaitForInputIdle();
            int tid = GetCurrentThreadId();
            int tidTo = prc.Threads[0].Id;
            if (!AttachThreadInput(tid, tidTo, true)) throw new Win32Exception();
            this.BringToFront();
            AttachThreadInput(tid, tidTo, false);
        }
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool AttachThreadInput(int tid, int tidTo, bool attach);
        [DllImport("kernel32.dll")]
        private static extern int GetCurrentThreadId();
    

提交回复
热议问题