我需要获得另一个窗口的句柄。
以下是代码:
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);
}
}
目前它可以找到&#34; Notepad&#34;没有问题,但GetWindowRect
函数将失败,并转到繁琐的错误消息处理代码,给我&#34;错误1400:无效的窗口句柄&#34;。
我做了一些搜索,但我找不到为什么它不起作用。我怀疑从static_cast
到IntPtr
的{{1}},代码来自互联网但似乎合法。
我也需要稍后操作的句柄。
答案 0 :(得分:1)
如果您知道窗口标题栏的名称,请尝试FindWindowA
HWND handle;
handle=FindWindowA(NULL, "Calculator");
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx