C# Pause After Bringing Application to Foreground

2019-08-21 08:42发布

问题:

I have a method that gets called into a new thread like so:

    if (!_isPlaying)
    {
        _playBackThread = new Thread(PlayMacroEvents);
        _playBackThread.Start();
        ...
    }

The method looks like:

Process proc = Process.GetProcessesByName("notepad").FirstOrDefault();
            if (proc != null)
            {
                SetForegroundWindow(proc.MainWindowHandle);
            }

            int loopCount = this.dsUserInput.Tables[0].Rows.Count;
            for (int i = 0; i < loopCount; i++)
            {
                foreach(MacroEvent macroEvent in _events)
                { 
                    Thread.Sleep(macroEvent.TimeSinceLastEvent);
                    switch (macroEvent.MacroEventType)
                    {
            ...

The problem I'm having is that if notepad is not already up (not minimized) there is enough delay between setting the foreground window and the macro output that often the first series of commands is not shown. How can I put enough of a pause to make sure that the window is up before the the macros start kicking in? A Thread.Sleep() between SetForegroundWindow() and the for loop does not seem to do the trick. Ideas?

回答1:

Use some api to get the active window, and wait until the window belonging to notepad is the active one



回答2:

The reason the first series of inputs were being dropped is because I also had to include the command to ShowWindow like so..

in the class header:

private const int SW_RESTORE = 9;
[DllImport("user32")]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
...

In the macro thread method I changed

    if (proc != null)
    {
        SetForegroundWindow(proc.MainWindowHandle);
    }

to look like:

   if (proc != null)
    {

        ShowWindow(proc.MainWindowHandle, SW_RESTORE);
        SetForegroundWindow(proc.MainWindowHandle);
    }