//查找线程是否启用
//AexeName:程序名称
//Myhwnd:返回找到的ProcessID
//返回值:True 找到了程序
function TFmain.FindExe(AexeName: string; var MyHwnd: THandle): Boolean;
var
ProcessName: string; // 进程名
FSnapshotHandle: THandle; // 进程快照句柄
FProcessEntry32: TProcessEntry32; // 进程入口的结构体信息
ContinueLoop: BOOL;
begin
Result := False;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // 创建一个进程快照
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); // 得到系统中第一个进程
// 循环例举
while ContinueLoop do
begin
ProcessName := FProcessEntry32.szExeFile;
if (LowerCase(ProcessName) = LowerCase(AexeName)) then
begin
MyHwnd := GetHWndByPID(FProcessEntry32.th32ProcessID);
Result := True;
break;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle); // 释放快照句柄
end;
// 跟据ProcessId获取进程的窗口句柄
function TFmain.GetHWndByPID(const hPID: THandle): THandle;
type
PEnumInfo = ^TEnumInfo;
TEnumInfo = record
ProcessID: DWORD;
HWND: THandle;
end;
function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): BOOL; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessID(Wnd, @PID);
Result := (PID <> EI.ProcessID) or (not IsWindowVisible(Wnd)) or (not IsWindowEnabled(Wnd));
if not Result then
EI.HWND := Wnd;
end;
function FindMainWindow(PID: DWORD): DWORD;
var
EI: TEnumInfo;
begin
EI.ProcessID := PID;
EI.HWND := 0;
EnumWindows(@EnumWindowsProc, Integer(@EI));
Result := EI.HWND;
end;
begin
if hPID <> 0 then
Result := FindMainWindow(hPID)
else
Result := 0;
end;
//XE10 帮助文件中的String与ShortString的转换
function ShortStringToString(Value: array of Byte): String;
var
B: TBytes;
L: Byte;
begin
Result := ‘‘;
L := Value[0];//获取ShortString长度 stortstring长度存在第一位当中
SetLength(B, L);
Move(Value[1], B[0], L);
Result := TEncoding.Ansi.GetString(B);
end;
procedure StringToShortString(const S: String; var RetVal);
var
L: Integer;
I: Byte;
C: Char;
P: PByte;
B: TBytes;
begin
L := Length(S);
if L > 255 then
raise EShortStringConvertError.Create(‘Strings longer than 255 characters cannot be converted‘);
// SetLength(B, L);
B := TEncoding.Ansi.GetBytes(S);
P := @RetVal;//P指向了RetVal 及shortstring类型的指针
P^ := Length(B);//P[0]存入数据长度
Inc(P);//移动指针
Move(B[0], P^, Length(B));//将内容存入到P
end;