gpt4 book ai didi

delphi - 如何使程序的第二个实例将控制权传递回第一个实例?

转载 作者:行者123 更新时间:2023-12-03 15:10:12 26 4
gpt4 key购买 nike

我已经使用 Delphi XE3 创建了一个应用程序。我的应用程序有一个托盘图标(我为此使用 TCoolTrayIcon),因此当用户最小化它时,任务栏上没有图标,而仅在托盘图标上。

为了避免我的应用程序出现多个实例,我使用以下代码:

procedure CreateMutexes(const MutexName: String);
const
SECURITY_DESCRIPTOR_REVISION = 1;
var
SecurityDesc: TSecurityDescriptor;
SecurityAttr: TSecurityAttributes;
MutexHandle: THandle;
begin
InitializeSecurityDescriptor(@SecurityDesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(@SecurityDesc, True, nil, False);
SecurityAttr.nLength := SizeOf(SecurityAttr);
SecurityAttr.lpSecurityDescriptor := @SecurityDesc;
SecurityAttr.bInheritHandle := False;
MutexHandle := CreateMutex(@SecurityAttr, False, PChar(MutexName));

if MutexHandle <> 0 then
begin
if GetLastError = ERROR_ALREADY_EXISTS then
begin
MessageBox(0, 'You cannot start more than one instance of ContLab.'
+ #13#10 + 'Use the instance has already started.',
'ContLab', mb_IconHand);

CloseHandle(MutexHandle);
Halt;
end
end;

CreateMutex(@SecurityAttr, False, PChar('Global\' + MutexName));
end;

这样,当用户启动应用程序两次时,他会收到错误消息,并且第二次实例将终止。

现在我不想显示错误消息,而是打开应用程序第一个实例的主窗体并终止第二个实例。

可能吗?

最佳答案

您需要向其他应用程序发送消息以请求它自行显示。

首先,您需要找到其他应用程序的主窗口。有很多方法可以做到这一点。例如,您可以使用FindWindow。或者您可以使用 EnumWindows 枚举顶级窗口。通常,您会检查匹配的窗口文本和/或类名称。

找到另一个实例的主窗口后,您需要赋予它将自身设置为前台窗口的能力。您需要调用AllowSetForegroundWindow

var
pid: DWORD;
....
GetWindowThreadProcessId(hwndOtherInstance, pid);
AllowSetForegroundWindow(pid);

然后向窗口发送用户定义的消息。例如:

const
WM_RESTOREWINDOW = WM_APP;
....
SendMessage(hwndOtherInstance, WM_RESTOREWINDOW, 0, 0);

最后,您的其他实例的主窗体需要监听此消息。

type
TMainForm = class(TForm)
....
protected
procedure WMRestoreWindow(var Message: TMessage); message WM_RESTOREWINDOW;
....
end;

当它遇到消息时,它必须执行以下操作:

procedure TMainForm.WMRestoreWindow(var Message: TMessage);
begin
inherited;
Visible := True;
Application.Restore;
Application.BringToFront;
end;
<小时/>

我对你的互斥体处理代码有点怀疑。我不明白安全属性的必要性,因为您是在本地命名空间中创建它。但随后我看到对 CreateMutex 的第二次调用忽略了返回值,但在全局命名空间中创建了一个对象。

关于delphi - 如何使程序的第二个实例将控制权传递回第一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22637936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com