Reputation: 169
I need to get the handle of another window.
Here is the code for it:
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);
}
}
Currently it can find the process which is "Notepad" without a problem, but GetWindowRect
function will fail, and goes to the cumbersome error message handling code, giving me "error 1400: Invalid window handle".
I have done some searching but I cannot find why it does not work. I suspect the static_cast
from IntPtr
to HWND
, the code is from internet but seems legit.
I need the handle for some later operations as well.
Upvotes: 3
Views: 12508
Reputation: 21
if u know the name of the title bar of the window then try FindWindowA
HWND handle;
handle=FindWindowA(NULL, "Calculator");
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx
Upvotes: 2