- Process Handles and Identifiers
- C++: Best way to get Window Handle of the only window from a process by process id, process handle and title name [duplicate]
- 1 Answer 1
- Как работать с процессами через Powershell Get-Process
- Как вывести детальную информацию через Powershell Get-Process
- Как отфильтровать процессы по утилизации в Powershell
- Запуск и остановка процессов через Powershell
- Get Window instance from Window Handle
- 2 Answers 2
- Using Window Procedures
- Designing a Window Procedure
- Associating a Window Procedure with a Window Class
- Subclassing a Window
Process Handles and Identifiers
When a new process is created by the CreateProcess function, handles of the new process and its primary thread are returned. These handles are created with full access rights, and — subject to security access checking — can be used in any of the functions that accept thread or process handles. These handles can be inherited by child processes, depending on the inheritance flag specified when they are created. The handles are valid until closed, even after the process or thread they represent has been terminated.
The CreateProcess function also returns an identifier that uniquely identifies the process throughout the system. A process can use the GetCurrentProcessId function to get its own process identifier (also known as the process ID or PID). The identifier is valid from the time the process is created until the process has been terminated. A process can use the Process32First function to obtain the process identifier of its parent process.
If you have a process identifier, you can get the process handle by calling the OpenProcess function. OpenProcess enables you to specify the handle’s access rights and whether it can be inherited.
A process can use the GetCurrentProcess function to retrieve a pseudo handle to its own process object. This pseudo handle is valid only for the calling process; it cannot be inherited or duplicated for use by other processes. To get the real handle to the process, call the DuplicateHandle function.
C++: Best way to get Window Handle of the only window from a process by process id, process handle and title name [duplicate]
I’m looking for the best way to get a Window Handle in the following situation:
I have the process id and process handle, I know the window titlename and I know that the process has only one window.
So how would I do it? FindWindow ? EnumWIndows ?
1 Answer 1
Using FindWindow requires that you either know the window class or the window title. Both of these are not necessarily unique. Since you alread have the process handle (and its ID) you can implement a robust solution using EnumWindows .
First, declare a structure used for communication. It passes a process ID to the enumeration procedure and returns the window handle back.
Next, we need a callback procedure that retrieves the process ID ( GetWindowThreadProcessId ) for any given window and compares it to the one we are looking for:
What’s left is the public interface. It populates the structure used for communication with the process ID, triggers the enumeration of top-level windows, and returns the window handle. The calls to SetLastError and GetLastError are required, since EnumWindows returns FALSE for both error and success in this case:
This will retrieve the first top-level window that matches a given process ID. Since the requirements state that there will only ever be a single window for the given process, the first one that matches is the correct window.
If additional restrictions exist, EnumProc can be expanded to include those. I have marked the spot in the implementation above, where additional filters can be applied.
Как работать с процессами через Powershell Get-Process
Командлет Powershell Get-Process возвращает все процессы запущенные на локальном компьютере. Команда пишется так:
Мы так же можем посмотреть так же процессы, запущенные на удаленном компьютере:
Но для того, что бы мы смогли это сделать удаленно у нас минимум должен быть включен WinRM. Если вы впервые слышите об этом, то вы можете прочитать об этом в этой статье. Так же добавлю, что ключ -ComputerName частый признак того, что мы можем выполнить команду удаленно.
Навигация по посту
Скорее всего мы хотим получить более детальную информацию или отфильтровать её. Если мы хотим получить информацию об экземплярах, достаточно заполнить ключ -Name:
Где:
-IncludeUserName — выведет имя того, кто запустил экземпляр.
Если мы не знаем имени, можно добавить * :
При этом если у вас запущено несколько процессов с этим именем, вернуться все.
Расшифрую заголовки:
- Handles — Дескриптор процесса, кто-то может знать под HWND. Уникальное число потока ввода — вывода.
- NPM(K) — Non-paged memory. Данные, которые не выгружаются на диск в килобайтах.
- PM(K) — Pageable memory. Данные, которые могут быть выгружены на диск в килобайтах.
- WS(K) — Process working set. Рабочий набор процесса или сумма всех страниц, которые на данный момент находятся в памяти в килобайтах.
- CPU(s) — время использованное процессом на всех процессорах в секундах.
- ID — идентификатор процесса, мы по нему можем фильтровать.
- SI — Session ID. Идентификатор сеанса где 0 — запущен для всех сессий, 1 — запущен для первого залогиненного пользователя, 2 — для следующего.
Попробуем преобразовать значение из килобайтов в мегабайты:
Где:
-Select-Object обозначаем столбцы, которые хотим вывести.
Как вывести детальную информацию через Powershell Get-Process
Что бы вывести всю возможную информацию два варианта. Это либо вывести объект в виде листа:
Либо можно объявить в переменную, получить все имена свойств и вызывать их по отдельности:
Под такой командой powershell я могу узнать имя, которое пишется в окошке:
Свойств, которые хранит объект процесса (то что мы видим при $result | Get-Member) очень много и это главное, к чему нужно обращаться когда мы хотим узнать подробнее об объекте.
Так мы выведем все запущенные процессы, у которых есть GUI:
Как отфильтровать процессы по утилизации в Powershell
Так мы увидим процессы, которые используют больше 67 Мб в памяти с дополнительной информацией о приоритете:
Таким командлетом мы получи информацию по одному процессу, у которого самое высокое значение CPU. Из свойств этого объекта выбран ID, Имя, CPU и время запуска.
Запуск и остановка процессов через Powershell
Мы можем остановить любой процесс. Например таким образом мы остановим все процессы, которые не отвечают (зависли):
Конечно мы можем остановить процесс по идентификатору или имени:
Таким командлетом мы остановим самый старый процесс:
Запуск экземпляра и его завершение через 5 секунд:
Все остальные команды можно узнать с помощью:
Справки с вариантами использования команд powershell:
Get Window instance from Window Handle
I am able get a Window handle from running applications using the following code.
But I want to get the Window instance from this handler. Is it possible?
Any quick idea please?
2 Answers 2
Try the following:
Update:
But this will work only inside the same AppDomain, because otherwise it would mean that you could share an object across different AppDomains and even processes, which is obviously impossible.
In a WPF application (or WinForms) there are two ‘objects’ (that is blocks of memory containing information) to a ‘window’:
- The system window object.
- The managed objects that ‘wraps’ the system object.
Access to the system window object is provided through the window handle (typeof HWND in unmanaged code, IntPtr in managed code). Given a window handle, which you already obtained, you can manipulate that window using the Window API methods. You can use p/invoke for this.
Access to the managed object, which resides in the heap of the process (or AppDomain in the case of a managed process) is forbidden. This memory is ‘protected’ from other processes(1).
The only way that objects can be shared between processes (or AppDomains) is through marshalling which is a cooperative effort on the part of both processes. This applies even to many of the Win32 API methods when accessing a window in another process. Not all access is possible without custom marshalling.
Note that unlike WinForms, WPF does not (normally) use system windows for controls. If your aim is to manipulate the visual tree in another WPF process/domain, you’re simply out of luck unless that process provides some sort of Automation interface.
(1) While it is possible to read the raw memory of another process, objects on a managed heap are moving targets. One could never even find them, even if you could somehow suspend the garbage collecting thread of that process.
Using Window Procedures
This section explains how to perform the following tasks associated with window procedures.
Designing a Window Procedure
The following example shows the structure of a typical window procedure. The window procedure uses the message argument in a switch statement with individual messages handled by separate case statements. Notice that each case returns a specific value for each message. For messages that it does not process, the window procedure calls the DefWindowProc function.
The WM_NCCREATE message is sent just after your window is created, but if an application responds to this message by returning FALSE, CreateWindowEx function fails. The WM_CREATE message is sent after your window is already created.
The WM_DESTROY message is sent when your window is about to be destroyed. The DestroyWindow function takes care of destroying any child windows of the window being destroyed. The WM_NCDESTROY message is sent just before a window is destroyed.
At the very least, a window procedure should process the WM_PAINT message to draw itself. Typically, it should handle mouse and keyboard messages as well. Consult the descriptions of individual messages to determine whether your window procedure should handle them.
Your application can call the DefWindowProc function as part of the processing of a message. In such a case, the application can modify the message parameters before passing the message to DefWindowProc, or it can continue with the default processing after performing its own operations.
A dialog box procedure receives a WM_INITDIALOG message instead of a WM_CREATE message and does not pass unprocessed messages to the DefDlgProc function. Otherwise, a dialog box procedure is exactly the same as a window procedure.
Associating a Window Procedure with a Window Class
You associate a window procedure with a window class when registering the class. You must fill a WNDCLASS structure with information about the class, and the lpfnWndProc member must specify the address of the window procedure. To register the class, pass the address of WNDCLASS structure to the RegisterClass function. After the window class has been registered, the window procedure is automatically associated with each new window created with that class.
The following example shows how to associate the window procedure in the previous example with a window class.
Subclassing a Window
To subclass an instance of a window, call the SetWindowLong function and specify the handle to the window to subclass the GWL_WNDPROC flag and a pointer to the subclass procedure. SetWindowLong returns a pointer to the original window procedure; use this pointer to pass messages to the original procedure. The subclass window procedure must use the CallWindowProc function to call the original window procedure.
To write code that is compatible with both 32-bit and 64-bit versions of Windows, use the SetWindowLongPtr function.
The following example shows how to subclass an instance of an edit control in a dialog box. The subclass window procedure enables the edit control to receive all keyboard input, including the ENTER and TAB keys, whenever the control has the input focus.