Форум: "WinAPI";
Текущий архив: 2004.05.02;
Скачать: [xml.tar.bz2];
ВнизПодскажите плз. как закрыть работающий Exe, лучше на примере? Найти похожие ветки
← →
mip © (2004-03-04 15:52) [0]Подскажите плз. как закрыть работающий Exe, лучше на примере?
← →
Digitman © (2004-03-04 16:09) [1]жмакаешь три веселых клавиши, открывается окно Диспетчера Задач, в этом окне в закладке "Процессы" ищешь процесс с именем совпадающим с именем ехе-файла и жмакаешь кнопулю "Завершить процесс" ... все)
← →
Polevi © (2004-03-04 16:34) [2]>Digitman © (04.03.04 16:09) [1]
слишком сложно, надо мышой подвести стрелочку к верхнему правому углу окошка, там будет крестик - давить на нем левый батон мыши.. все
← →
Klev (2004-03-04 16:34) [3]The TerminateProcess function terminates the specified process and all of its threads.
BOOL TerminateProcess(
HANDLE hProcess, // handle to the process
UINT uExitCode // exit code for the process
);
Parameters
hProcess
Identifies the process to terminate.
Windows NT: The handle must have PROCESS_TERMINATE access. For more information, see Process Objects.
uExitCode
Specifies the exit code for the process and for all threads terminated as a result of this call. Use the GetExitCodeProcess
function to retrieve the process"s exit value. Use the GetExitCodeThread function to retrieve a thread"s exit value.
Return Values
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
The TerminateProcess function is used to unconditionally cause a process to exit. Use it only in extreme circumstances. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.
TerminateProcess causes all threads within a process to terminate, and causes a process to exit, but DLLs attached to the process are not notified that the process is terminating.
Terminating a process causes the following:
1. All of the object handles opened by the process are closed.
2. All of the threads in the process terminate their execution.
3. The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.
4. The states of all threads of the process become signaled, satisfying any threads that had been waiting for the threads to terminate.
5. The termination status of the process changes from STILL_ACTIVE to the exit value of the process.
Terminating a process does not cause child processes to be terminated.
Terminating a process does not necessarily remove the process object from the system. A process object is deleted when the last handle to the process is closed.
See Also
ExitProcess, OpenProcess, GetExitCodeProcess, GetExitCodeThread
Ну а для того, что бы узнать hprocess(сначала processid):
The GetWindowThreadProcessId function retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window. This function supersedes the GetWindowTask function.
DWORD GetWindowThreadProcessId(
HWND hWnd, // handle of window
LPDWORD lpdwProcessId // address of variable for process identifier
);
Parameters
hWnd
Identifies the window.
lpdwProcessId
Points to a 32-bit value that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the 32-bit value; otherwise, it does not.
Return Values
The return value is the identifier of the thread that created the window.
и полученный processid передать в качестве пареметра следующей функции:
The OpenProcess function returns a handle of an existing process object.
HANDLE OpenProcess(
DWORD dwDesiredAccess, // access flag
BOOL bInheritHandle, // handle inheritance flag
DWORD dwProcessId // process identifier
);
Parameters
dwDesiredAccess
Specifies the access to the process object. For operating systems that support security checking, this access is checked against any security descriptor for the target process. Any combination of the following access flags can be specified in addition to the STANDARD_RIGHTS_REQUIRED access flags:
Access Description
PROCESS_ALL_ACCESS Specifies all possible access flags for the process object.
PROCESS_CREATE_PROCESS Used internally.
PROCESS_CREATE_THREAD Enables using the process handle in the CreateRemoteThread function to create a thread in the process.
PROCESS_DUP_HANDLE Enables using the process handle as either the source or target process in the DuplicateHandle function to duplicate a handle.
PROCESS_QUERY_INFORMATION Enables using the process handle in the GetExitCodeProcess and GetPriorityClass functions to read information from the process object.
PROCESS_SET_INFORMATION Enables using the process handle in the SetPriorityClass function to set the priority class of the process.
PROCESS_TERMINATE Enables using the process handle in the TerminateProcess function to terminate the process.
PROCESS_VM_OPERATION Enables using the process handle in the VirtualProtectEx and WriteProcessMemory functions to modify the virtual memory of the process.
PROCESS_VM_READ Enables using the process handle in the ReadProcessMemory function to read from the virtual memory of the process.
PROCESS_VM_WRITE Enables using the process handle in the WriteProcessMemory function to write to the virtual memory of the process.
SYNCHRONIZE Windows NT only: Enables using the process handle in any of the wait functions to wait for the process to terminate.
bInheritHandle
Specifies whether the returned handle can be inherited by a new process created by the current process. If TRUE, the handle is inheritable.
dwProcessId
Specifies the process identifier of the process to open.
Return Values
If the function succeeds, the return value is an open handle of the specified process.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The handle returned by the OpenProcess function can be used in any function that requires a handle to a process, such as the wait functions, provided the appropriate access rights were requested.
When you are finished with the handle, be sure to close it using the CloseHandle function.
примерчик:
procedure terminate; :)
var hprocess,procid:dword;
begin
GetWindowThreadProcessId(findwindow(nil,pchar("Kill_me!)),procid);
hProcess:=OpenProcess(PROCESS_CREATE_THREAD or PROCESS_VM_WRITE or process_terminate or
PROCESS_VM_OPERATION, FALSE, procid);
terminateprocess(hprocess,0);
closehandle(hprocess);
end;
Ну вот собственно и все.
← →
Vit@ly © (2004-03-04 16:51) [4]GetWindowText(Wnd, buff, sizeof(buff));
PostMessage(FindWindow(Nil,pchar(StrPas(buff))), WM_QUIT, 0, 0);
← →
Alexander666 © (2004-03-05 03:35) [5]TerminateProcess использовать нежелательно, только в критических случаях, когда уже ничего не помогает.
← →
evvcom (2004-03-05 08:15) [6]
> Vit@ly © (04.03.04 16:51) [4]
> GetWindowText(Wnd, buff, sizeof(buff));
> PostMessage(FindWindow(Nil,pchar(StrPas(buff))), WM_QUIT, 0, 0);
Интересное решение. Wnd - это Handle, который и нужен для PostMessage. А конструкция GetWindowText с последующим FindWindow наталкивает на мысль, что автор хочет найти тот же самый Wnd, но дело в том, что в системе может быть несколько окон с одинаковым именем, и Handle которого из них вернет FindWindow заранее неизвестно. Поэтому будьте осторожны с этой функцией. Нужны дополнительные проверки.
Если Handle главного окна известен, то делается просто PostMessage(hWnd, WM_QUIT, 0, 0);
← →
GrayFace © (2004-03-05 16:35) [7]Vit@ly, не смешно.
← →
Klev (2004-03-05 19:22) [8]>Vit@ly © (04.03.04 16:51) [4]
Интересное решение :))))
>GrayFace © (05.03.04 16:35) [7] - смешно
Передай в качестве параметра то, незнаю что. Результат пошли туда, незнаю куда.
← →
Vit@ly © (2004-03-06 12:29) [9]Вам, что необходимо представить полный код (мне показалось это тривиальным)?
Это легко возможно реализовать. В цикле выведите все окна, в любой контрол (ListBox). И по клику удаляйте любой "работающий ЕХЕ" (так сформулировано в вопросе.
Очень долго ЛОЛ GrayFace © (05.03.04 16:35) [7] и Klev (05.03.04 19:22) [8]
Если есть необходимость могу написать подробно
← →
DDA © (2004-03-06 20:11) [10]
function KillTask(ExeFileName: string): integer;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot
(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle,
FProcessEntry32);
while integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeFileName))
or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(OpenProcess(
PROCESS_TERMINATE, BOOL(0),
FProcessEntry32.th32ProcessID), 0));
ContinueLoop := Process32Next(FSnapshotHandle,
FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
← →
Игорь Шевченко © (2004-03-06 20:16) [11]
> Result := Integer(TerminateProcess(OpenProcess(
> PROCESS_TERMINATE, BOOL(0),
> FProcessEntry32.th32ProcessID), 0));
А ошибки проверять Пушкин будет ?
← →
DDA © (2004-03-06 20:28) [12]прекрасно работает
← →
YurikGl © (2004-03-06 20:50) [13]Удалено модератором
Примечание: Offtopic
Страницы: 1 вся ветка
Форум: "WinAPI";
Текущий архив: 2004.05.02;
Скачать: [xml.tar.bz2];
Память: 0.49 MB
Время: 0.034 c