Delphi 窗体置前(设置窗体靠前/激活)的几个方法
1、方法一:
function BringWindowToTopEx(hWnd: HWND): Boolean;
begin
if IsIconic(hWnd) then
ShowWindow(hWnd, SW_RESTORE);
if GetForegroundWindow <> hWnd then
SetForegroundWindow(hWnd); //enabled
//BringWindowToTop(hWnd);//not enabled
//ForceForegroundWindow(hWnd);//enabled
{SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);//enabled}
//SwitchToThisWindow(hWnd, True);//enabled
Result := GetForegroundWindow = hWnd;
end;
function BringWindowToTopMost(hWnd: HWND; bTopMost: Boolean): Boolean;
begin
if IsIconic(hWnd) then
ShowWindow(hWnd, SW_RESTORE);
if bTopMost then
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE)
else
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
end;
function BringWindowToTopXY(hWnd: HWND; X, Y: Integer; hWndInsertAfter: HWND): Boolean;
begin
Result := BringWindowToTopEx(hWnd);
Result := SetWindowPos(hWnd, hWndInsertAfter, X, Y, 0, 0, SWP_NOSIZE) and Result;
end;
2、方法二:
// 窗体置顶
procedure SetXwForegroundWindow(AHandle: Thandle);
var
hFgWin: Thandle;
hFgThread: Thandle;
begin
ShowWindow(AHandle, SW_NORMAL);
hFgWin := GetForegroundWindow;
hFgThread := GetWindowThreadProcessID(hFgWin, nil);
if AttachThreadInput(GetCurrentThreadID, hFgThread, true) then
begin
SetForegroundWindow(AHandle);
AttachThreadInput(GetCurrentThreadID, hFgThread, false);
end
else
SetForegroundWindow(AHandle);
end;
// 激活窗体
function SetSysFocus(AHandle: Thandle): boolean;
var
hThreadId: Thandle;
hFgThreadId: Thandle;
begin
result := false;
if not IsWindow(AHandle) then
exit;
hThreadId := GetWindowThreadProcessID(AHandle, nil);
hFgThreadId := GetWindowThreadProcessID(GetForegroundWindow, nil);
if AttachThreadInput(hThreadId, hFgThreadId, true) then
begin
SetFocus(AHandle);
AttachThreadInput(hThreadId, hFgThreadId, false);
end
else
SetFocus(AHandle);
result := true;
end;
3、方法三:
窗体函数 WinAPI SwitchToThisWindow
https://www.cnblogs.com/guorongtao/p/13440024.html
创建时间:2020.08.05 更新时间: