C#暂停后将应用程序带到前台输入

时间:2010-10-19 23:12:05

标签: c# multithreading macros

我有一个被调用到新线程的方法,如下所示:

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

该方法如下:

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)
                    {
            ...

我遇到的问题是,如果记事本尚未启动(未最小化),则在设置前景窗口和宏输出之间有足够的延迟,通常不会显示第一系列命令。在宏开始启动之前,我怎样才能确保窗口已启动? Thread.Sleep()SetForegroundWindow()循环之间的for似乎无法解决问题。想法?

2 个答案:

答案 0 :(得分:1)

使用一些api获取活动窗口,并等到属于记事本的窗口是活动窗口

答案 1 :(得分:0)

第一系列输入被删除的原因是因为我还必须将命令包含在ShowWindow中,因此......

在类标题中:

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

在宏线程方法中我改变了

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

看起来像:

   if (proc != null)
    {

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