怎么让一个应用程序只创建一次,在关闭前,如果双击它的图标只激活这程序的主窗体

如何让一个应用程序只创建一次,在关闭前,如果双击它的图标只激活这程序的主窗体
如何让一个应用程序只创建一次,在关闭前,如果双击它的图标只激活这程序的主窗体

------解决方案--------------------
// usage: just add this unit to your project
unit ZsSingleInstance;

interface

procedure SingleInstance;

implementation

uses Windows, Messages, Forms;

type
PShareMem = ^TShareMem;
TShareMem = record
AppHandle: THandle;
end;

var
GMapFileHandle: THandle;
GShareMem: PShareMem;

procedure InitMapFile;
const MAP_FILE_NAME = '{D96D0544-6ADB-408F-9EEF-D1694264C955} ';// please change it to your own unique GUID
begin
// try to open file mapping
GMapFileHandle := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(MAP_FILE_NAME));
// first run
if GMapFileHandle = 0 then begin
GMapFileHandle := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, SizeOf(TShareMem), MAP_FILE_NAME);
GShareMem := MapViewOfFile(GMapFileHandle, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
if GShareMem = nil then CloseHandle(GMapFileHandle)
else GShareMem^.AppHandle := 0;// set previous app handle to 0 if first run
end
else begin// get previous instance shared mem
GShareMem := MapViewOfFile(GMapFileHandle, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
if GShareMem = nil then CloseHandle(GMapFileHandle);
end;
end;

procedure SingleInstance;
var top_window: HWND;
begin
try
if GShareMem <> nil then begin
if GShareMem^.AppHandle = 0 then GShareMem^.AppHandle := Application.Handle
else begin
SendMessage(GShareMem^.AppHandle, WM_SYSCOMMAND, SC_RESTORE, 0);
top_window := GetLastActivePopup(GShareMem^.AppHandle);
if (top_window <> 0) and
(top_window <> GShareMem^.AppHandle) and
IsWindowVisible(top_window) and
IsWindowEnabled(top_window) then
SetForegroundWindow(top_window);// restore last active window
// terminate current instance
Halt(0);
end;
end;
except end;
end;

initialization
try// open or create map file
InitMapFile;
SingleInstance;
except end;

finalization
try// free map file
UnMapViewOfFile(GShareMem);
CloseHandle(GMapFileHandle);
except end;

end.