如何让Window对话窗口重新获得输入焦点

很多情况下,自动弹出程序的对话框可能没有自动获得输入焦点。这样就需要通过手动鼠标,或者快捷键切换到该窗口。

可以通过下面的过程,在检测到对话框弹出的时候,自动获得输入焦点,便于输入新的信息。

程序中利用了Timer,一秒钟检测输入对话框是否出现,如果出现了,便做如下的事情:

Created with Raphaël 2.2.0 一秒钟中断开始 对话框是否在前台? 对话框是否在当前屏幕中心? 退出一秒钟中断 将对话框调入当前屏幕中心 将对话框调入前台, 并获取输入焦点 yes no yes no
  static int nInputLineFormVisible = 0;
    if(InputLineForm->Visible && nInputLineFormVisible == 0) {
        Beep(2000, 50);
        nInputLineFormVisible = 1;

        SetForegroundWindow(MemoForm->Handle);
        HWND hCurWnd = ::GetForegroundWindow();
        DWORD dwMyID = ::GetCurrentThreadId();
        DWORD dwCurID = ::GetWindowThreadProcessId(hCurWnd, NULL);
        ::AttachThreadInput(dwCurID, dwMyID, TRUE);
        ::SetForegroundWindow(InputLineForm->Handle);
        ::AttachThreadInput(dwCurID, dwMyID, FALSE);

        TPoint point;
        GetCursorPos(&point);
        if(Screen->MonitorCount >= 2) {
            int i;
            for(i = 0; i < Screen->MonitorCount; i ++) {
                int nMonitorCenterX = Screen->Monitors[i]->Left +
                              Screen->Monitors[i]->Width / 2;
                int nMonitorCenterY = Screen->Monitors[i]->Top +
                               Screen->Monitors[i]->Height / 2;

                int nBox[4];
                nBox[0] = Screen->Monitors[i]->Left;
                nBox[1] = Screen->Monitors[i]->Top;
                nBox[2] = Screen->Monitors[i]->Left + Screen->Monitors[i]->Width;
                nBox[3] = Screen->Monitors[i]->Top + Screen->Monitors[i]->Height;

                if(PointInBox(point.x, point.y, nBox)) {
                    int nDialogLeft = nMonitorCenterX - InputLineForm->Width / 2;
                    int nDialogTop = nMonitorCenterY - InputLineForm->Height / 2;
                    if(nDialogLeft != InputLineForm->Left ||
                       nDialogTop != InputLineForm->Top) {
                        InputLineForm->Left = nDialogLeft;
                        InputLineForm->Top = nDialogTop;
                    }
                    break;
                }
            }
        }
    } else if(InputLineForm->Visible == false)
        nInputLineFormVisible = 0;
发布了464 篇原创文章 · 获赞 552 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zhuoqingjoking97298/article/details/105677508