通過exe名字查詢句柄,String與ShortString轉換函數分析
//查找線程是否啟用
//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;
通過exe名字查詢句柄,String與ShortString轉換函數分析