program MyThreadTest;
uses
Windows
Forms
SysUtils
Messages
Dialogs
Unit in Unitpas {Form}
{$R *res}
var
myMutex
FindHid: HWND;
MoudleName: string;
function EnumWndProc(hwnd: Thandle; param: Cardinal): bool; stdcall;
//由于用于api回调函数请使用windows传统的参数传递方式stdcall
var
ClassName WinMoudleName: string;
WinInstance: THandle;
begin
result := true;
SetLength(ClassName );
GetClassName(hwnd pchar(ClassName) length(ClassName)); //获得当前遍历窗口的类名
ClassName := pchar(ClassName); //在字符串后加结束符确定字符串结束
if UpperCase(ClassName) = UpperCase(TFormClassName) then //比较类名
begin
WinInstance := GetWindowLong(hwnd GWL_HINSTANCE); //获得当前遍历窗口的实例
setlength(WinMoudleName );
//获得当前遍历窗口的程序文件名
GetModuleFileName(WinInstance pchar(WinMoudleName) length(WinMoudleName));
WinMoudleName := pchar(WinMoudleName);
WinMoudleName :=ExtractFileName(WinMoudleName);
//MoudleName为工程全局变量自身程序的文件名
if UpperCase(WinMoudleName) = UpperCase(MoudleName) then
begin
FindHid := hwnd;//FindHid为工程全局变量保存找到的句炳
result := false; //找到以后就结束遍历
end;
end;
end;
begin
// CreateMutex建立互斥对象并且给互斥对象起一个唯一的名字
myMutex := CreateMutex(nil false hkOneCopy);
if WaitForSingleObject(myMutex ) <> wait_TimeOut then
//程序没有被运行过
begin
ApplicationInitialize;
ApplicationCreateForm(TForm Form);
ApplicationRun;
end else
begin
SetLength(MoudleName );
//获得自己程序文件名
GetModuleFileName(HInstance pchar(MoudleName) length(MoudleName));
MoudleName := pchar(MoudleName);
MoudleName := ExtractFileName(MoudleName);
EnumWindows(@EnumWndProc ); //调用枚举函数
if FindHid <> then
begin
ShowWindow(FindHidSW_RESTORE);
SetForegroundWindow(FindHid);
end;
end;
end
[EnumWindows函数使用]
EnumWindows 用来列举屏幕上所有顶层窗口
MSDN
The EnumWindows function enumerates all toplevel windows on the screen by passing the handle to each window
[] [] []