Экспертная система Delphi.int.ru

Сообщество программистов
Общение, помощь, обмен опытом

Логин:
Пароль:
Регистрация | Забыли пароль?

Delphi.int.ru Expert

Другие разделы портала

Переход к вопросу:

#   

Статистика за сегодня:  


Лучшие эксперты

Подробнее »



Вопрос # 2 027

/ вопрос открыт /

Приветствую, уважаемые эксперты!!! Доброго времени суток!
Подскажите как мне узнать какие процессы запущены в системе(в том числе и системные), узнать от куда они запущены и вывести эту информацию в ListBox?
Заранее спасибо.

Приложение:
  1. Delphi 7, Windows XP Pro SP2


Фоминых Сергей Николаевич Вопрос ожидает решения (принимаются ответы, доступен мини-форум)

Вопрос задал: Фоминых Сергей Николаевич (статус: Посетитель)
Вопрос отправлен: 29 октября 2008, 17:58
Состояние вопроса: открыт, ответов: 3.

Ответ #1. Отвечает эксперт: Аксион

Здравствуйте, Фоминых Сергей Николаевич!
Посмотрите вот этот, замечательный пример.
https://www.delphi-int.ru/download/file/162/
Process Killers
Программа для завершения процессов. Показывает абсолютно всё запущеное на компьютере.
+ её исходник.

Ответ отправил: Аксион (статус: 4-ый класс)
Время отправки: 29 октября 2008, 18:43

Ответ #2. Отвечает эксперт: Feniks

Здравствуйте, Фоминых Сергей Николаевич!
Держите в приложении несколько примерчиков:
1. Просмотрщик запущенных процессов;
2. Как получить список процессов;
3. Как определить какие приложения уже запущены;
4. Прочитать список всех запущенных Exe/ Проверить запущен ли Exe;
5. Как определить откуда был запущен процесс.

P.S. Желаю удачи.

Приложение:
  1.  
  2. uses
  3. Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  4. ExtCtrls, tlhelp32, StdCtrls, ComCtrls, Buttons;
  5.  
  6. type
  7. TForm1 = class(TForm)
  8. ListBox1: TListBox;
  9. Button1: TButton;
  10. Button2: TButton;
  11. Button4: TButton;
  12. Button5: TButton;
  13. StatusBar1: TStatusBar;
  14. Button6: TButton;
  15. procedure Button4Click(Sender: TObject);
  16. procedure FormCreate(Sender: TObject);
  17. procedure Button2Click(Sender: TObject);
  18. procedure Button1Click(Sender: TObject);
  19. procedure Button5Click(Sender: TObject);
  20. procedure ListBox1Click(Sender: TObject);
  21. procedure Button6Click(Sender: TObject);
  22. private
  23. { Private declarations }
  24. procedure ListProcesses;
  25. procedure Delproc(numb:string);
  26. public
  27. { Public declarations }
  28. end;
  29.  
  30. var
  31. Form1: TForm1;
  32. processID:array[1..50] of integer;
  33.  
  34. function RegisterServiceProcess(dwProcessID,dwType:integer):integer;stdcall;external 'kernel32.dll';
  35.  
  36. implementation
  37.  
  38. {$R *.DFM}
  39.  
  40. procedure TForm1.delproc(numb:string);
  41. var
  42. c1:Cardinal;
  43. pe:TProcessEntry32;
  44. s1,s2:string;
  45. x:integer;
  46. begin
  47. x:=0;
  48. try
  49. Strtoint(numb);
  50. except
  51. Statusbar1.SimpleText:='Invalid number';
  52. exit;
  53. end;
  54. c1:=CreateToolHelp32Snapshot(TH32CS_SnapProcess,0);
  55. if c1=INVALID_HANDLE_VALUE then
  56. begin
  57. Statusbar1.SimpleText:='Process listing failed';
  58. exit;
  59. end;
  60. try
  61. pe.dwSize:=sizeof(pe);
  62. if Process32First(c1,pe) then
  63. repeat
  64. inc(x);
  65. s1:=ExtractFileName(pe.szExeFile);
  66. s2:=ExtractFileExt(s1);
  67. Delete(s1,length(s1)+1-length(s2),maxInt);
  68. if x=strtoint(numb) then
  69. if terminateprocess(OpenProcess(PROCESS_ALL_ACCESS,false,pe.th32ProcessID),1)
  70. then begin
  71. Statusbar1.SimpleText:='Process '+s1+' terminated.';
  72. end
  73. else Statusbar1.SimpleText:=('Couldnt terminate process'+pe.szExeFile);
  74. until not Process32Next(c1,pe);
  75. finally CloseHandle(c1);
  76. end;
  77. end;
  78.  
  79. procedure Tform1.ListProcesses;
  80. var c1:Cardinal;
  81. pe:TProcessEntry32;
  82. s1,s2:string;
  83. x:integer;
  84. begin
  85. X:=0;
  86. c1:=CreateToolHelp32Snapshot(TH32CS_SnapProcess,0);
  87. if c1=INVALID_HANDLE_VALUE then
  88. begin
  89.  
  90. exit;
  91. end;
  92. try
  93. pe.dwSize:=sizeof(pe);
  94. if Process32First(c1,pe) then
  95. repeat
  96. inc(x);
  97. s1:=ExtractFileName(pe.szExeFile);
  98. s2:=ExtractFileExt(s1);
  99. Delete(s1,length(s1)+1-length(s2),maxInt);
  100. Listbox1.Items.Add(Inttostr(x)+' '+s1+' : '+pe.szExeFile);
  101. ProcessId[x]:=pe.th32ProcessID;
  102. //ListBox1.Items.Add(inttostr(pe.th32ProcessID));
  103. until not Process32Next(c1,pe);
  104. finally CloseHandle(c1);
  105. end;
  106.  
  107. end;
  108.  
  109.  
  110.  
  111. procedure TForm1.Button4Click(Sender: TObject);
  112. begin
  113. Close;
  114. end;
  115.  
  116. procedure TForm1.FormCreate(Sender: TObject);
  117. begin
  118. Button1.Enabled:=false;
  119. Button5.Enabled:=false;
  120. Button6.Enabled:=false;
  121. ListProcesses;
  122. if not (csDesigning in ComponentState) then
  123. RegisterServiceProcess(GetCurrentProcessID,1);
  124. end;
  125.  
  126. procedure TForm1.Button2Click(Sender: TObject);
  127. begin
  128. Listbox1.Clear;
  129. ListProcesses;
  130. end;
  131.  
  132. procedure TForm1.Button1Click(Sender: TObject);
  133. var p:integer;
  134. begin
  135. //hide
  136. with Listbox1 do
  137. p:=Listbox1.Items.IndexOf(Listbox1.items[itemindex])+1;
  138. if not (csDesigning in ComponentState) then
  139. RegisterServiceProcess(ProcessID[p],1);
  140. with Listbox1 do
  141. StatusBar1.SimpleText:=(Listbox1.items[itemindex]+ ' hidden');
  142. end;
  143.  
  144. procedure TForm1.Button5Click(Sender: TObject);
  145. var p:integer;
  146. begin
  147. //show
  148. with Listbox1 do
  149. p:=Listbox1.Items.IndexOf(Listbox1.items[itemindex])+1;
  150. if not (csDesigning in ComponentState) then
  151. RegisterServiceProcess(ProcessID[p],0);
  152. with Listbox1 do
  153. StatusBar1.SimpleText:=(Listbox1.items[itemindex]+ ' shown');
  154. end;
  155.  
  156. procedure TForm1.ListBox1Click(Sender: TObject);
  157. begin
  158. Button1.Enabled:=true;
  159. Button5.Enabled:=true;
  160. Button6.Enabled:=true;
  161. end;
  162.  
  163. procedure TForm1.Button6Click(Sender: TObject);
  164. var p:integer;
  165. begin
  166. with Listbox1 do
  167. p:=Listbox1.Items.IndexOf(Listbox1.items[itemindex])+1;
  168. delproc(inttostr(p));
  169. end;
  170.  
  171. end.
  172.  
  173.  
  174.  
  175. function IsRunning( sName : string ) : boolean;
  176. var
  177. han : THandle;
  178. ProcStruct : PROCESSENTRY32; // from "tlhelp32" in uses clause
  179. sID : string;
  180. begin
  181. Result := false;
  182. // Get a snapshot of the system
  183. han := CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 );
  184. if han = 0 then
  185. exit;
  186. // Loop thru the processes until we find it or hit the end
  187. ProcStruct.dwSize := sizeof( PROCESSENTRY32 );
  188. if Process32First( han, ProcStruct ) then
  189. begin
  190. repeat
  191. sID := ExtractFileName( ProcStruct.szExeFile );
  192. // Check only against the portion of the name supplied, ignoring case
  193. if uppercase( copy( sId, 1, length( sName ) ) ) = uppercase( sName ) then
  194. begin
  195. // Report we found it
  196. Result := true;
  197. Break;
  198. end;
  199. until not Process32Next( han, ProcStruct );
  200. end;
  201. // clean-up
  202. CloseHandle( han );
  203. end;
  204.  
  205.  
  206.  
  207. procedure TForm1.Button1Click(Sender: TObject);
  208. VAR
  209. Wnd : hWnd;
  210. buff: ARRAY [0..127] OF Char;
  211. begin
  212. ListBox1.Clear;
  213. Wnd := GetWindow(Handle, gw_HWndFirst);
  214. WHILE Wnd <> 0 DO
  215.  
  216.  
  217.  
  218.  
  219.  
  220. THEN BEGIN
  221. GetWindowText(Wnd, buff, sizeof(buff));
  222. ListBox1.Items.Add(StrPas(buff));
  223. END;
  224. Wnd := GetWindow(Wnd, gw_hWndNext);
  225. END;
  226. ListBox1.ItemIndex := 0;
  227. end;
  228.  
  229.  
  230.  
  231. uses
  232. Psapi, tlhelp32;
  233.  
  234. procedure CreateWin9xProcessList(List: TstringList);
  235. var
  236. hSnapShot: THandle;
  237. ProcInfo: TProcessEntry32;
  238. begin
  239. if List = nil then Exit;
  240. hSnapShot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  241. if (hSnapShot <> THandle(-1)) then
  242. begin
  243. ProcInfo.dwSize := SizeOf(ProcInfo);
  244. if (Process32First(hSnapshot, ProcInfo)) then
  245. begin
  246. List.Add(ProcInfo.szExeFile);
  247. while (Process32Next(hSnapShot, ProcInfo)) do
  248. List.Add(ProcInfo.szExeFile);
  249. end;
  250. CloseHandle(hSnapShot);
  251. end;
  252. end;
  253.  
  254. procedure CreateWinNTProcessList(List: TstringList);
  255. var
  256. PIDArray: array [0..1023] of DWORD;
  257. cb: DWORD;
  258. I: Integer;
  259. ProcCount: Integer;
  260. hMod: HMODULE;
  261. hProcess: THandle;
  262. ModuleName: array [0..300] of Char;
  263. begin
  264. if List = nil then Exit;
  265. EnumProcesses(@PIDArray, SizeOf(PIDArray), cb);
  266. ProcCount := cb div SizeOf(DWORD);
  267. for I := 0 to ProcCount - 1 do
  268. begin
  269. hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or
  270. PROCESS_VM_READ,
  271. False,
  272. PIDArray[I]);
  273. if (hProcess <> 0) then
  274. begin
  275. EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cb);
  276. GetModuleFilenameEx(hProcess, hMod, ModuleName, SizeOf(ModuleName));
  277. List.Add(ModuleName);
  278. CloseHandle(hProcess);
  279. end;
  280. end;
  281. end;
  282.  
  283. procedure GetProcessList(var List: TstringList);
  284. var
  285. ovi: TOSVersionInfo;
  286. begin
  287. if List = nil then Exit;
  288. ovi.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  289. GetVersionEx(ovi);
  290. case ovi.dwPlatformId of
  291. VER_PLATFORM_WIN32_WINDOWS: CreateWin9xProcessList(List);
  292. VER_PLATFORM_WIN32_NT: CreateWinNTProcessList(List);
  293. end
  294. end;
  295.  
  296. function EXE_Running(FileName: string; bFullpath: Boolean): Boolean;
  297. var
  298. i: Integer;
  299. MyProcList: TstringList;
  300. begin
  301. MyProcList := TStringList.Create;
  302. try
  303. GetProcessList(MyProcList);
  304. Result := False;
  305. if MyProcList = nil then Exit;
  306. for i := 0 to MyProcList.Count - 1 do
  307. begin
  308. if not bFullpath then
  309. begin
  310. if CompareText(ExtractFileName(MyProcList.Strings[i]), FileName) = 0 then
  311. Result := True
  312. end
  313. else if CompareText(MyProcList.strings[i], FileName) = 0 then Result := True;
  314. if Result then Break;
  315. end;
  316. finally
  317. MyProcList.Free;
  318. end;
  319. end;
  320.  
  321.  
  322. // Example 1: Is a Exe-File running ?
  323. procedure TForm1.Button1Click(Sender: TObject);
  324. begin
  325. if EXE_Running('Notepad.exe', False) then
  326. ShowMessage('EXE is running')
  327. else
  328. ShowMessage('EXE is not running');
  329. end;
  330.  
  331.  
  332. // Example 2: List running Exe-Files
  333. procedure TForm1.Button3Click(Sender: TObject);
  334. var
  335. i: Integer;
  336. MyProcList: TstringList;
  337. begin
  338. MyProcList := TStringList.Create;
  339. try
  340. GetProcessList(MyProcList);
  341. if MyProcList = nil then Exit;
  342. for i := 0 to MyProcList.Count - 1 do
  343. ListBox1.Items.Add(MyProcList.Strings[i]);
  344. finally
  345. MyProcList.Free;
  346. end;
  347. end;
  348.  
  349.  
  350.  
  351. uses
  352. tlhelp32;
  353.  
  354. type
  355. TModuleArray = array of TModuleEntry32;
  356.  
  357.  
  358. function GetModulesListByProcessId(ProcessId : Cardinal) : TModuleArray;
  359.  
  360. implementation
  361.  
  362. function GetModulesListByProcessId(ProcessId : Cardinal) : TModuleArray;
  363. var
  364. hSnapshot : THandle;
  365. lpme : TModuleEntry32;
  366.  
  367. procedure AddModuleToList;
  368. begin
  369. SetLength(Result,High(Result)+2);
  370. Result[high(Result)]:=lpme;
  371. end;
  372.  
  373. begin
  374. SetLength(Result,0);
  375. hSnapshot:=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,ProcessId);
  376. if hSnapshot=-1 then RaiseLastWin32Error;
  377. lpme.dwSize:=SizeOf(lpme);
  378. if Module32First(hSnapshot,lpme) then
  379. begin
  380. AddModuleToList;
  381. while Module32Next(hSnapshot,lpme) do AddModuleToList;
  382. end;
  383. end;
  384.  
  385.  
  386. VAR Wnd : hWnd;
  387. buff: ARRAY [0..127] OF Char;
  388. //------------------------------------
  389. Pid : Cardinal;
  390. modarr : TModuleArray;
  391. Name : String;
  392. //------------------------------------
  393. begin
  394. StringGrid1.RowCount:=1;
  395. Wnd := GetWindow(Handle, gw_HWndFirst);
  396. WHILE Wnd <> 0 DO
  397. BEGIN
  398. IF (GetWindowText(Wnd, buff, sizeof(buff)) <> 0) THEN
  399. BEGIN
  400. fillchar(name,sizeof(name),#0);
  401. GetWindowText(wnd,buff,sizeof(buff));
  402. // if getmodulefilename(GetWindowLong(wnd,GWL_HINSTANCE),name,sizeof(name))=0
  403. // then name:='Null';
  404. //-----------------------------------------
  405. GetWindowThreadProcessId(Wnd,@Pid);
  406. modarr:=GetModulesListByProcessId(Pid);
  407. name:='Null';
  408. for i:=0 to High(modarr) do
  409. begin
  410. if Integer(modarr[i].modBaseAddr)=$400000 then
  411. begin
  412. name:=modarr[i].szExePath;
  413. break;
  414. end;
  415. end;
  416. //-----------------------------------------
  417. StringGrid1.Cells[0,StringGrid1.RowCount-1]:=StrPas(buff);
  418. StringGrid1.Cells[1,StringGrid1.RowCount-1]:=StrPas(name);
  419. StringGrid1.RowCount:=StringGrid1.RowCount+1;
  420. END;
  421. Wnd := GetWindow(Wnd, gw_hWndNext);
  422. END;
  423. StringGrid1.RowCount:=StringGrid1.RowCount-1;
  424. end;


Ответ отправил: Feniks (статус: Бакалавр)
Время отправки: 29 октября 2008, 19:02

Ответ #3. Отвечает эксперт: seryoga

Здравствуйте, Фоминых Сергей Николаевич!
Вот пример кода

Приложение:
  1. uses
  2. Psapi, tlhelp32;
  3.  
  4. procedure CreateWin9xProcessList(List: TstringList);
  5. var
  6. hSnapShot: THandle;
  7. ProcInfo: TProcessEntry32;
  8. begin
  9. if List = nil then Exit;
  10. hSnapShot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  11. if (hSnapShot <> THandle(-1)) then
  12. begin
  13. ProcInfo.dwSize := SizeOf(ProcInfo);
  14. if (Process32First(hSnapshot, ProcInfo)) then
  15. begin
  16. List.Add(ProcInfo.szExeFile);
  17. while (Process32Next(hSnapShot, ProcInfo)) do
  18. List.Add(ProcInfo.szExeFile);
  19. end;
  20. CloseHandle(hSnapShot);
  21. end;
  22. end;
  23.  
  24. procedure CreateWinNTProcessList(List: TstringList);
  25. var
  26. PIDArray: array [0..1023] of DWORD;
  27. cb: DWORD;
  28. I: Integer;
  29. ProcCount: Integer;
  30. hMod: HMODULE;
  31. hProcess: THandle;
  32. ModuleName: array [0..300] of Char;
  33. begin
  34. if List = nil then Exit;
  35. EnumProcesses(@PIDArray, SizeOf(PIDArray), cb);
  36. ProcCount := cb div SizeOf(DWORD);
  37. for I := 0 to ProcCount - 1 do
  38. begin
  39. hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or
  40. PROCESS_VM_READ,
  41. False,
  42. PIDArray[I]);
  43. if (hProcess <> 0) then
  44. begin
  45. EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cb);
  46. GetModuleFilenameEx(hProcess, hMod, ModuleName, SizeOf(ModuleName));
  47. List.Add(ModuleName);
  48. CloseHandle(hProcess);
  49. end;
  50. end;
  51. end;
  52.  
  53. procedure GetProcessList(var List: TstringList);
  54. var
  55. ovi: TOSVersionInfo;
  56. begin
  57. if List = nil then Exit;
  58. ovi.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  59. GetVersionEx(ovi);
  60. case ovi.dwPlatformId of
  61. VER_PLATFORM_WIN32_WINDOWS: CreateWin9xProcessList(List);
  62. VER_PLATFORM_WIN32_NT: CreateWinNTProcessList(List);
  63. end
  64. end;
  65.  
  66. function EXE_Running(FileName: string; bFullpath: Boolean): Boolean;
  67. var
  68. i: Integer;
  69. MyProcList: TstringList;
  70. begin
  71. MyProcList := TStringList.Create;
  72. try
  73. GetProcessList(MyProcList);
  74. Result := False;
  75. if MyProcList = nil then Exit;
  76. for i := 0 to MyProcList.Count - 1 do
  77. begin
  78. if not bFullpath then
  79. begin
  80. if CompareText(ExtractFileName(MyProcList.Strings[i]), FileName) = 0 then
  81. Result := True
  82. end
  83. else if CompareText(MyProcList.strings[i], FileName) = 0 then Result := True;
  84. if Result then Break;
  85. end;
  86. finally
  87. MyProcList.Free;
  88. end;
  89. end;
  90.  
  91.  
  92. // Example 1: Is a Exe-File running ?
  93. procedure TForm1.Button1Click(Sender: TObject);
  94. begin
  95. if EXE_Running('Notepad.exe', False) then
  96. ShowMessage('EXE is running')
  97. else
  98. ShowMessage('EXE is not running');
  99. end;
  100.  
  101.  
  102. // Example 2: List running Exe-Files
  103. procedure TForm1.Button3Click(Sender: TObject);
  104. var
  105. i: Integer;
  106. MyProcList: TstringList;
  107. begin
  108. MyProcList := TStringList.Create;
  109. try
  110. GetProcessList(MyProcList);
  111. if MyProcList = nil then Exit;
  112. for i := 0 to MyProcList.Count - 1 do
  113. ListBox1.Items.Add(MyProcList.Strings[i]);
  114. finally
  115. MyProcList.Free;
  116. end;
  117. end;
  118.  
  119.  


Ответ отправил: seryoga (статус: 1-ый класс)
Время отправки: 29 октября 2008, 19:34


Мини-форум вопроса

Всего сообщений: 2; последнее сообщение — 29 октября 2008, 19:39; участников в обсуждении: 2.
Вадим К

Вадим К (статус: Академик), 29 октября 2008, 19:09 [#1]:

to Блазер.
Говоришь, абсолютно всё? даже вирусы? Я не был бы столь оптимистичен.
Галочка "подтверждения прочтения" - вселенское зло.
Аксион

Аксион (статус: 4-ый класс), 29 октября 2008, 19:39 [#2]:

Вадим К, это я скопировал с описания.

Чтобы оставлять сообщения в мини-форумах, Вы должны авторизироваться на сайте.

Версия движка: 2.6+ (26.01.2011)
Текущее время: 22 февраля 2025, 11:40
Выполнено за 0.03 сек.