首页 | 社区 | 博客 | 招聘 | 文章 | 新闻 | 下载 | 读书 | 代码
亲,您未登录哦! 登录 | 注册

防止多个实例公用程序

打印文章

分享到:
将以下代码保存为MultInst.pas, 然后在任何Project的
Main Form中Uses MultInst, 就可以完善防止程序的多个
实例同时运行, 特与大家共享.

unit MultInst;

interface

const
MI_QUERYWINDOWHANDLE   = 1;
MI_RESPONDWINDOWHANDLE = 2;

MI_ERROR_NONE          = 0;
MI_ERROR_FAILSUBCLASS  = 1;
MI_ERROR_CREATINGMUTEX = 2;

function GetMIError: Integer;

implementation

uses Forms, Windows, SysUtils;

const
UniqueAppStr = 'DDG.I_Am_Winger!';

var
MessageId: Integer;
WProc: TFNWndProc;
MutHandle: THandle;
MIError: Integer;

function GetMIError: Integer;
begin
Result := MIError;
end;

function NewWndProc(Handle: HWND; Msg: Integer; wParam, lParam: Longint): Longint; stdcall;
begin
Result := 0;
if Msg = MessageId then
case wParam of
MI_QUERYWINDOWHANDLE:
begin
if IsIconic(Application.Handle) then
begin
Application.MainForm.WindowState := wsNormal;
Application.Restore;
end;
PostMessage(HWND(lParam), MessageId, MI_RESPONDWINDOWHANDLE, Application.MainForm.Handle);
end;
MI_RESPONDWINDOWHANDLE:
begin
SetForegroundWindow(HWND(lParam));
Application.Terminate;
end;
end
else
Result := CallWindowProc(WProc, Handle, Msg, wParam, lParam);
end;

procedure SubClassApplication;
begin
WProc := TFNWndProc(SetWindowLong(Application.Handle, GWL_WNDPROC, LongInt(@NewWndProc)));
if WProc = nil then MIError := MIError or MI_ERROR_FAILSUBCLASS;
end;

procedure DoFirstInstance;
begin
MutHandle := CreateMutex(nil, False, UniqueAppStr);
if MutHandle = 0 then MIError := MI_ERROR_CREATINGMUTEX;
end;

procedure BroadcastFocusMessage;
var
BSMRecipients: DWORD;
begin
Application.ShowMainForm := False;
BSMRecipients := BSM_APPLICATIONS;
BroadCastSystemMessage(BSF_IGNORECURRENTTASK or BSF_POSTMESSAGE,
@BSMRecipients, MessageId, MI_QUERYWINDOWHANDLE, Application.Handle);
end;

procedure InitInstance;
begin
SubClassApplication;
MutHandle := OpenMutex(MUTEX_ALL_ACCESS, False, UniqueAppStr);
if MutHandle = 0 then DoFirstInstance
else BroadcastFocusMessage;
end;

Initialization
MessageId := RegisterWindowMessage(UniqueAppStr);
InitInstance;
finalization
if WProc <> nil then SetWindowLong(Application.Handle, GWL_WNDPROC, LongInt(WProc));
if MutHandle <> 0 then CloseHandle(MutHandle);
end.

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( Pfan.cn )

编程爱好者论坛

本栏最新文章