如何防止程序运行多个例程? (100分)

  • 主题发起人 主题发起人 fanwei
  • 开始时间 开始时间
<a href="http://www.gislab.ecnu.edu.cn/delphibbs/DispQ.asp?LID=142451">http://www.gislab.ecnu.edu.cn/delphibbs/DispQ.asp?LID=142451</a>
 
//copy from borland// :)
var
hMutex : Thandle;
WaitResult : word;
BroadcastList : DWORD;
begin
MessageID := RegisterWindowMessage('Check For Choice Previous Inst');
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 &amp;
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;
 
来自Inprise新闻组:
{there are several approaches to preventing multiple instances of an
application. The one I favour is the following: make sure your main
form has a unique name that is unlikely to crop up an any other
application. then
on your projects DPR file, before any of your
forms is created, youdo
a }
If FindWindow( Pchar(TMyMainform.Classname), Nil ) then
Exit;

{This prevents the second instance from ever coming up. If you have the
additional goal of activating the first instance, use a slightly different
approach:}
hPrevWindow := FindWindow( Pchar(TMyMainform.Classname), Nil );
If hPrevWindow <> 0 then
begin
PostMessage( hPrevWindow, UM_ACTIVATEFIRSTINSTANCE, 0, 0 );
Exit;
end;


{UM_ACTIVATEFIRSTINSTANCE is a constant (WM_USER + something) you define in
the interface section of your main forms unit. The main form also gets a
handler for this message:}
private
Procedure UMActivateFirstInstance( Var msg: TMessage );
message UM_ACTIVATEFIRSTINSTANCE;

{implemented as}
Procedure TMyMainform.UMActivateFirstInstance( Var msg: TMessage );
begin
If IsIconic(Application.Handle) then
Application.restore;
BringTofront;

end;


{That's all there is to it. }
{Peter Below (TeamB)}
 
mail to me :xiaocai@263.net ,I'll tell you!
 
见者有分!
 
多人接受答案了。
 
后退
顶部