【问题标题】:C# Pause After Bringing Application to Foreground for Input将应用程序带到前台进行输入后 C# 暂停
【发布时间】:2010-10-19 23:12:04
【问题描述】:

我有一个方法可以像这样被调用到一个新线程中:

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

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

【问题讨论】:

  • 其余代码会发生什么? “宏”如何影响记事本?另请阅读 MSDN 中 SetForegroundWindow() 的小字,它经常失败。

标签: c# multithreading macros


【解决方案1】:

第一系列输入被删除的原因是因为我还必须像这样将命令包含到 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);
    }

【讨论】:

    【解决方案2】:

    使用一些api获取活动窗口,等待属于记事本的窗口成为活动窗口

    【讨论】:

    • 忽略了无限循环的可能性,我输入了以下代码,它仍然跳过了第一行文本输入。 IntPtr activeWindowHandle = GetForegroundWindow(); while ((!activeWindowHandle.Equals(proc.MainWindowHandle))) { if (!activeWindowHandle.Equals(proc.MainWindowHandle)) { activeWindowHandle = GetForegroundWindow(); } }
    • 嗯,可能是别的东西。如果您手动确保记事本是前台窗口,并且您不调用 SetForegroundWindow,那么一切是否都按预期执行? (使用计时器或类似工具)
    • 我发现发生的事情是,无论我睡多久,应用程序(记事本)总是在 thread.sleep 之后出现,即使在 thread.sleep 之前调用 GetForegroundWindow .
    • 我终于想通了!我还需要调用 ShowWindow user32 方法(在 SetForegroundWindow 之前)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多