FindWindow找不到窗口

时间:2013-05-13 20:48:39

标签: c++ winapi visual-c++

嘿伙计们我打算用C ++制作一个简单的教练控制台,但第一步我遇到了FindWindow()的问题

#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\n");
        getch();
    }
    else{
        printf("NOT FOUND");
        getch();
    }
}

上面的代码我用来尝试命令FindWindow()但是当我执行输出时总是显示

  

未找到

我已从

的属性Project替换了字符集
  

使用Unicode字符集

  

使用多字节字符集

  

LPCTSTR

  

LPCSTR

  

LPCWSTR

但结果总是一样,我希望有人能帮助我。

4 个答案:

答案 0 :(得分:12)

FindWindow只有具有指定标题的窗口才会找到,而不仅仅是子字符串。

或者你可以:


搜索窗口类名称:

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

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

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 :(得分:8)

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

答案 2 :(得分:2)

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

示例:

Google - Mozilla Firefox

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

答案 3 :(得分:1)

根据MSDN

  

lpWindowName [in,optional]

Type: LPCTSTR

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

因此,您的WindowName不能成为&#34; Mozilla Firefox&#34;,因为Firefox窗口的标题永远不会是&#34; Mozilla Firefox&#34;但它可能是&#34; Mozilla Firefox Start Page - Mozilla Firefox&#34;或者某些东西取决于网页的名称。 这是示例图片 Firefox's real tiltle

因此,您的代码应该是这样的(下面的代码只能工作 - 只能工作如果您有确切的窗口标题名称:&#34; Mozilla Firefox Start Page - Mozilla Firefox&#34;就像上面的图片一样。我已经在Windows 8.1上进行了测试,但它确实有效)

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.
}
相关问题