关于c ++:FindWindow找不到窗口

FindWindow does not find the a window

大家好,我打算用C ++创建一个简单的培训控制台,但是第一步,我遇到了FindWindow()问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <cstdlib>
#include <windows.h>
#include <winuser.h>
#include <conio.h>

LPCTSTR WindowName ="Mozilla Firefox";
HWND Find = FindWindow(NULL,WindowName);
int main(){
    if(Find)
    {
        printf("FOUND
"
);
        getch();
    }
    else{
        printf("NOT FOUND");
        getch();
    }
}

上面的代码用于尝试命令FindWindow()是否执行,但在执行输出时始终显示

NOT FOUND

我已经从

Use Unicode Character Set

Use Multi-Byte Character Set

LPCTSTR

LPCSTR

要么

LPCWSTR

但是结果总是一样的,我希望任何人都能帮助我。


FindWindow仅在具有完全指定的标题的情况下找到窗口,而不仅仅是子字符串。

或者,您可以:

搜索窗口类名称:

1
HWND hWnd = FindWindow("MozillaWindowClass", 0);

枚举所有窗口,并对标题执行自定义模式搜索:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    char buffer[128];
    int written = GetWindowTextA(hwnd, buffer, 128);
    if (written && strstr(buffer,"Mozilla Firefox") != NULL) {
        *(HWND*)lParam = hwnd;
        return FALSE;
    }
    return TRUE;
}

HWND GetFirefoxHwnd()
{
    HWND hWnd = NULL;
    EnumWindows(EnumWindowsProc, &hWnd);
    return hWnd;
}


1
 HWND Find = ::FindWindowEx(0, 0,"MozillaUIWindowClass", 0);


您需要使用应用程序的全名(如Windows任务管理器->"应用程序"选项卡所示)

例:

Google - Mozilla Firefox

(在Firefox中打开Goog??le标签后)


根据MSDN

lpWindowName [in, optional]

1
2
3
Type: LPCTSTR

The window name (the window's title). If this parameter is NULL, all window names match.

因此,您的WindowName不能是" Mozilla Firefox",因为Firefox窗口的标题永远不会是" Mozilla Firefox",而可能是" Mozilla Firefox起始页-Mozilla Firefox"或某些取决于网页名称的东西。
这是示例图片
Firefoxs real tiltle

因此,您的代码应该是这样的(以下代码仅适用-仅当您具有确切的窗口标题名称时才能使用:" Mozilla Firefox起始页-Mozilla Firefox",如上图所示。我已经在Windows 8.1上进行了测试,并且可以正常工作)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void CaptureWindow()
{


RECT rc;
HWND hwnd = ::FindWindow(0, _T("Mozilla Firefox Start Page - Mozilla Firefox"));//::FindWindow(0,_T("ScreenCapture (Running) - Microsoft Visual Studio"));//::FindWindow(0, _T("Calculator"));//= FindWindow("Notepad", NULL);    //You get the ideal?
if (hwnd == NULL)
{
    return;
}
GetClientRect(hwnd, &rc);

//create
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
    rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);

//Print to memory hdc
PrintWindow(hwnd, hdc, PW_CLIENTONLY);

//copy to clipboard
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();

//release
DeleteDC(hdc);
DeleteObject(hbmp);
ReleaseDC(NULL, hdcScreen);

//Play(TEXT("photoclick.wav"));//This is just a function to play a sound, you can write it yourself, but it doesn't matter in this example so I comment it out.
}