+ -
当前位置:首页 → 问答吧 → 如何用windows Api判断是不是主窗口?

如何用windows Api判断是不是主窗口?

时间:2011-09-20

来源:互联网

判断一个句柄是否为主窗口可以用两种方法
1. GetParent(hwnd) == NULL
2. GetWindows(hwnd, GW_OWNER) == NULL
具体:http://zwkufo.blog.163.com/blog/static/258825120104717513/
我发现这两种方法都不是很准确,有时对有时错。
请问有什么更精确的方法吗?多谢

作者: donkey301   发布时间: 2011-09-20

Delphi(Pascal) code

wndInfo=packed record 
    dwProcessId:DWORD;
    hWind:HWND;
end;
LPWNDINFO=^wndInfo;

function EnumWindowsProc(
  hwnd: HWND; 
  lParam: LPARAM
): BOOL; stdcall;
var
  vProcessID: THandle;
  vBuffer: array[0..255] of Char;
  nStyle:integer;
  pInfo:LPWNDINFO;
begin
  Result:= true;
  GetWindowThreadProcessId(hwnd, vProcessID);
  pInfo:=LPWNDINFO(lParam);
    if vProcessID = pInfo.dwProcessId then
    begin
        nStyle:=GetWindowLong(hWnd,GWL_HWNDPARENT);
        if nStyle=0 then
          Result:=True
        else
        begin
          pInfo.hWind:=nStyle;
          Result:=FALSE;
        end;
    end;
end;
function GetProcessMainWnd(dwProcessId:DWORD):HWND;
var
    Dwnd:wndInfo;
begin
    wi.dwProcessId:=dwProcessId;
    wi.wnd:=HWND(nil);
    EnumWindows(@EnumWindowsProc,LPARAM(@Dwnd));
    result:=Dwnd.hWind;
end;


MSDN上解释:
GWL_HWNDPARENT->Retrieves a handle to the parent window, if any.

作者: m617105   发布时间: 2011-09-20

引用 1 楼 m617105 的回复:

Delphi(Pascal) code

wndInfo=packed record
dwProcessId:DWORD;
hWind:HWND;
end;
LPWNDINFO=^wndInfo;

function EnumWindowsProc(
hwnd: HWND;
lParam: LPARAM
): BOOL; stdcall;
var
vProces……

多谢,试了一下,GetWindowLong(hWnd,GWL_HWNDPARENT)和GetWindow(hWnd, GWL_OWNER)一样的结果,有些程序依然错误

作者: donkey301   发布时间: 2011-09-20