以焦点启动Windows应用程序

时间:2012-06-13 05:17:01

标签: winapi visual-c++

我正在使用没有MVC的Visual C ++编写一个小型Windows应用程序。它非常小,它只包含一个文本字段,一个OK按钮和一个取消按钮。

当用户开始打印时,应用程序由后台进程启动。打开应用程序时无法获得焦点,甚至看不到。

对于用户而言,应用程序是直接关注的,因此他们可以使用租借点击来使用它。

我尝试了许多方法来使应用程序成为焦点:

SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
SetForegroundWindow(hWnd);
ShowWindow(hWnd, SW_RESTORE);
SetFocus(hWnd);

我甚至在计时器中重复了这个电话。所有这一切都行不通。现在我在MSDN上发现了一些评论:

  

系统限制哪些进程可以设置前景窗口。一个   只有在以下情况之一时,进程才能设置前台窗口   条件是真的:

The process is the foreground process.
The process was started by the foreground process.
The process received the last input event.
There is no foreground process.
The foreground process is being debugged.
The foreground is not locked (see LockSetForegroundWindow).
The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
No menus are active.

有人知道解决方法吗?

3 个答案:

答案 0 :(得分:4)

没有解决方法。这种新的Windows行为的全部意义在于防止应用程序将自己置于前台并成为一种麻烦。在您的情况下,我建议使用通知图标,并在必要时显示气球消息而不是窗口。但是,即使在这种情况下,您的通知图标也可以由用户隐藏,并且没有解决方法,原因与上述相同。

答案 1 :(得分:0)

现在,这是来自Java开发人员,而不是Visual C ++开发人员,但您是否可以设置框架/窗口/其他所谓的visual-c始终位于顶部?在Java中,如果您有JFrame,说myJFrame,则可以调用myJFrame.setAlwaysOnTop(true)并保持在所有其他窗口之上。这似乎是解决您问题的一个简单方法,但如果用户在屏幕上屏蔽了他们的某些内容,则可能不适合。

答案 2 :(得分:0)

http://www.thescarms.com/vbasic/alttab.aspx似乎可以胜任

void forceToFront(HWND hWnd) {
HWND foregroundWindow = GetForegroundWindow();

if (foregroundWindow == hWnd) {
    // Window is already Foreground-window
    return;
}

if (SetForegroundWindow(hWnd)) {
    // could set window to foreground without any tricks
    return;
}

// attach thread of foreground-window to this window
DWORD foregroundThread = GetWindowThreadProcessId(foregroundWindow, NULL);
DWORD myThread = GetWindowThreadProcessId(hWnd, NULL);
AttachThreadInput(foregroundThread, myThread, true);
SetForegroundWindow(hWnd);
AttachThreadInput(foregroundThread, myThread, false);

}