-
Notifications
You must be signed in to change notification settings - Fork 78
/
unRunOne.pas
90 lines (77 loc) · 1.94 KB
/
unRunOne.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
unit unRunOne;
interface
(* 程序是否已经运行,如果运行则激活它 *)
function AppHasRun(AppHandle: THandle; MapFileName: string): Boolean;
implementation
uses
Windows, Forms, Messages;
type
//共享内存
PShareMem = ^TShareMem;
TShareMem = record
AppHandle: THandle; //保存程序的句柄
end;
var
hMapFile: THandle;
PSMem: PShareMem;
procedure CreateMapFile(MapFileName: string);
begin
hMapFile := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(MapFileName));
if hMapFile = 0 then
begin
hMapFile := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,
SizeOf(TShareMem), PChar(MapFileName));
PSMem := MapViewOfFile(hMapFile, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
if PSMem = nil then
begin
CloseHandle(hMapFile);
Exit;
end;
PSMem^.AppHandle := 0;
end
else
begin
PSMem := MapViewOfFile(hMapFile, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
if PSMem = nil then
begin
CloseHandle(hMapFile);
end
end;
end;
procedure FreeMapFile;
begin
UnMapViewOfFile(PSMem);
CloseHandle(hMapFile);
end;
// MapFileName 当前值只允许运行一个进程,每个应用取一个不同的值
function AppHasRun(AppHandle: THandle; MapFileName: string): Boolean;
var
TopWindow: HWnd;
begin
//创建句柄
CreateMapFile(MapFileName);
Result := False;
if PSMem <> nil then
begin
if PSMem^.AppHandle <> 0 then
begin
SendMessage(PSMem^.AppHandle, WM_SYSCOMMAND, SC_RESTORE, 0);
TopWindow := GetLastActivePopup(PSMem^.AppHandle);
if (TopWindow <> 0) and (TopWindow <> PSMem^.AppHandle) and
IsWindowVisible(TopWindow) and IsWindowEnabled(TopWindow) then
begin
SetForegroundWindow(TopWindow);
end;
// MessageBox(0, '该程序已经运行中!','提示', MB_OK+MB_ICONINFORMATION);
Application.Terminate;
Result := True;
end
else
PSMem^.AppHandle := AppHandle;
end;
end;
initialization
// CreateMapFile;
finalization
FreeMapFile;
end.