发信人: redfox (Z掉了几乎所有的版...), 信区: BorlandDev
标 题: Delphi编程 -- 6.16 防止程序运行多个例程
发信站: 哈工大紫丁香 (2000年09月01日16:27:17 星期五), 站内信件
防止程序运行多个例程?
More than one instance of program?
回答
This is copied direct from my *.dpr file. You can work it for your
own
use.
var
hMutex : Thandle;
WaitResult : word;
BroadcastList : DWORD;
begin
MessageID := RegisterWindowMessage('Check For Choice Previous
Inst');
// register a message to use later on
hMutex := createMutex(nil,false,pchar('App_Choice')); // grab a
mutex
handle
WaitResult := WaitForSingleObject(hMutex,10); // wait to see
if we can have exclusive use of the mutex
if ( waitResult = WAIT_TIMEOUT ) then // if we can't then
broadcast
the message to make the owner of the mutex respond
{ request that the running application takes focus }
begin
BroadcastList := BSM_APPLICATIONS;
BroadcastSystemMessage(
BSF_POSTMESSAGE,@BroadcastList,MessageID,0,0); //32 bit - broadcast
the
message to all apps - only a prev inst will hear it.
end
else
begin
{ do the normal stuff}
Application.Title := 'Choice Organics Purchase & Sales System';
Application.CreateForm(TMainForm, MainForm);
Application.Run;
ReleaseMutex(hMutex); // release the mutex as a politeness
end;
CloseHandle(hMutex); // close the mutex handle
end.
This goes in the MainForm
procedure Tmainform.OnAppMessage(var Msg : TMsg ; Var Handled :
Boolean);
begin
{ If it's the special message then focus on this window}
if Msg.Message = MessageID then // if we get the broadcast message
from an
another instance of this app that is trying to start up
begin
show;
WindowState := wsMaximized;
BringToFront;
SetFocus;
Handled := true;
end;
end;
//And this goes in the TMainForm.FormCreate ;-
Application.OnMessage:= OnAppMessage;
--
※ 来源:·哈工大紫丁香 bbs.hit.edu.cn·[FROM: 202.118.227.107]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:3.791毫秒