gpt4 book ai didi

c++-cli - CLI/C++ 如何获取窗口句柄?

转载 作者:行者123 更新时间:2023-12-04 16:48:53 43 4
gpt4 key购买 nike

我需要获取另一个窗口的句柄。

这是它的代码:

private: System::Void btn_find_Click(System::Object^  sender, System::EventArgs^  e) {
array<Process^>^ ps = Process::GetProcessesByName("Notepad");
IntPtr X = ps[0]->MainWindowHandle;
LPRECT rect;
if (GetWindowRect(static_cast<HWND>(X.ToPointer()), rect)){
DEBUGBOX->Text = "OK!";
}
else
{
//DEBUGBOX is a text box
DEBUGBOX->Text = ps[0]->MainWindowTitle;

//the following code is from MSDN, it is used to
//show a message box about the error
//P.S. I have no idea why it has to be this complicated
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
LPTSTR lpszFunction = TEXT("GetWindowRect");
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
using MessageBox = System::Windows::Forms::MessageBox;
MessageBox::Show(gcnew System::String((LPCTSTR)lpDisplayBuf));
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
}

目前它可以毫无问题地找到“记事本”进程,但是GetWindowRect函数会失败,并转到繁琐的错误信息处理代码,给我“error 1400: Invalid window handle ".

我进行了一些搜索,但找不到它不起作用的原因。我怀疑 IntPtrHWNDstatic_cast,代码来自互联网,但看起来是合法的。

我还需要句柄来进行一些后续操作。

最佳答案

如果你知道窗口标题栏的名称然后尝试FindWindowA

HWND handle;
handle=FindWindowA(NULL, "Calculator");

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx

关于c++-cli - CLI/C++ 如何获取窗口句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885816/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com