How to get HWND of the currently active Windows Explorer window?

烈酒焚心 提交于 2019-12-04 19:35:07

You can get the currently active window via GetForegroundWindow(). You could then do GetWindowThreadProcessId() to get a PID which you can then convert to a process handle with OpenProcess() (you will want PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights) and then you can check the process name with GetModuleFileNameEx(). Don't remember to close the process handle afterwards with CloseHandle().

Here's some code I just wrote in notepad. You'd probably do something along these lines.

DWORD  lpFileName[MAX_PATH] = {0};
DWORD  dwPID;
HANDLE hProcess;
HWND   hwnd = GetForegroundWindow();
GetWindowThreadProcessId( hwnd, &dwPID );
hProcess = OpenProcess( PROCESS_QUERY_INFOMRATION | PROCESS_VM_READ, false, dwPID );
GetModuleFileNameEx( hProcess, NULL, lpFileName, _countof( lpFileName ) );
PathStripPath( lpFileName );

if( _tcscmp( _T("explorer.exe"), lpFileName ) == 0 ) {
  _tprintf( _T("explorer window found") );
} else {
  _tprintf( _T("foreground window was not explorer window") );
}
CloseHandle( hProcess );

To get all open explorer windows you can use EnumWindows() which you provide a callback which receives all the top-level windows. You can then filter out however you want, maybe by process name (above), maybe by class name (GetClassName()).

Nick Spreitzer

Well, if you're certain that a Windows Explorer window is currently the foreground window you can use GetForegroundWindow. Otherwise, I think you'd have to enumerate through all windows until you've found the top-most Explorer window. Here's an example that I wrote up of how to enumerate through all windows*. Then, according to this SO thread, you can use GetWindowThreadProcessId to filter windows owned by Explorer.

*It's been a while, but I think EnumWindows iterates from the top of the z-order to the bottom.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!