是这样的程序本身是个托盘程序,为了解决程序启动的时候,隐藏主窗体,并且不让他闪动,我在程序中写了
Application.ShowMainForm := False;但是我现在还有一个要求是让托盘程序只能单实例运行,也就是只能运行一个!如果采用 handle := Windows.FindWindow(nil, 'FrmAppServer');
这样的方法肯定找不到,请问该怎么解决这个问题
Application.ShowMainForm := False;但是我现在还有一个要求是让托盘程序只能单实例运行,也就是只能运行一个!如果采用 handle := Windows.FindWindow(nil, 'FrmAppServer');
这样的方法肯定找不到,请问该怎么解决这个问题
//项目文件...beginApplication.initialation;if CreateMutex then beginApplication.CreateForm(Form1, TForm1);Application.Run;end elseDestroyMutex;end;//主窗体文件...implementationvarMutex: hWnd;function CreateMutex: Boolean;varPrevInstHandle: THandle;AppTitle: PChar;beginAppTitle := StrAlloc(100);StrPCopy(AppTitle, Application.Title);Result := True;Mutex := Windows.CreateMutex(nil, False, AppTitle);if (GetLastError = ERROR_ALREADY_EXISTS) or (Mutex = 0) then beginResult := False;SetWindowText(Application.Handle, '');PrevInstHandle := FindWindow(nil, AppTitle);if PrevInstHandle <> 0 then beginif IsIconic(PrevInstHandle) thenShowWindow(PrevInstHandle, SW_RESTORE)elseBringWindowToTop(PrevInstHandle);SetForegroundWindow(PrevInstHandle);end;if Mutex <> 0 thenMutex := 0;end;StrDispose(AppTitle);end;procedure DestroyMutex;beginif Mutex <> 0 thenCloseHandle(Mutex);end;
procedure TForm1.FormShow(Sender: TObject);varatom: Integer;beginif GlobalFindAtom('a random string here') = 0 thenatom := GlobalAddAtom('a random string here')elsebeginShowMessage('This application will run once a windows-session' + #13 +'Restart Your computer to use this app');Close;end;end;
使用全局原子://声明一下,下面代码的原作者是:王靖;
program Pvdde;
uses
Forms,shellapi,Windows,dialogs,dde in 'dde.pas' {Form1};
{$R *.RES}
begin
if GlobalFindAtom(PChar('PDDE_IS_RUNNING')) = 0 then
//避免二次启动
begin
K:=GlobalAddAtom(PChar('PDDE_IS_RUNNING'));
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
begin
//传递二次启动时的参数到第一个实例
H := FindWindow(PChar('TForm1'), PChar('资料保密 严禁外传'));
if ParamCount > 0 then
begin
L := GlobalAddAtom(PChar(ParamStr(1)));
if H<>0 then
SendMessage(H, WM_MYMESSAGE, 0, L);
{ 传递原子句柄 }
GlobalDeleteAtom(L); { 使用后释放 }
end;
Application.Terminate;
end;
end.在相应的窗口单元dde.pas增加对自定义消息WM_MYMESSAGE的处理:
procedure TForm1.MyMessage(var T:TMessage);
{对 WM_MYMESSAGE消息进行处理 }
var
P:Array [0..255] of char;
begin
GlobalGetAtomName(T.LParam, P,255); { 接受数据到p数组中 }
end;
最后注意自己程序关的时候,消掉托盘