На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

Installing and Releasing Hook Procedures



You can install a hook procedure by calling the SetWindowsHookEx function and specifying the type of hook calling the procedure, whether the procedure should be associated with all threads or with a particular thread, and a pointer to a procedure entry point.

You must place a global hook procedure in a DLL separate from the application installing the hook procedure. The installing application must have the handle of the DLL module before it can install the hook procedure. The LoadLibrary function, when given the name of the DLL, returns the handle of the DLL module. After you have the handle, you can call the GetProcAddress function to retrieve the address of the hook procedure. Finally, you use SetWindowsHookEx to install the hook procedure address in the appropriate hook chain. SetWindowsHookEx passes the module handle, a pointer to the hook-procedure entry point, and 0 for the thread identifier, indicating that the hook procedure should be associated with all threads in the system. This sequence is shown in the following example.

HOOKPROC hkprcSysMsg;
static HINSTANCE hinstDLL;
static HHOOK hhookSysMsg;

hinstDLL = LoadLibrary((LPCTSTR) "c:\\windows\\sysmsg.dll");
hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "SysMessageProc");
hhookSysMsg = SetWindowsHookEx(WH_SYSMSGFILTER,
hkprcSysMsg, hinstDLL, 0);


You can release a thread-specific hook procedure (remove its address from the hook chain) by calling the UnhookWindowsHookEx function, specifying the handle of the hook procedure to release. Release a hook procedure as soon as your application no longer needs it.
You can release a global hook procedure by using UnhookWindowsHookEx, but this function does not free the DLL containing the hook procedure. This is because global hook procedures are called in the process context of every application in the system, causing an implicit call to the LoadLibrary function for all of those processes. Because a call to the FreeLibrary function cannot be made for another process, there is then no way to free the DLL. Windows eventually frees the DLL after all processes explicitly linked to the DLL have either terminated or called FreeLibrary and all processes that called the hook procedure have resumed processing outside the DLL.

An alternative method for installing a global hook procedure is to provide an installation function in the DLL, along with the hook procedure. With this method, the installing application does not need the handle of the DLL module. By linking with the DLL, the application gains access to the installation function. The installation function can supply the DLL module handle and other details in the call to SetWindowsHookEx. The DLL can also contain a function that releases the global hook procedure; the application can call this hook-releasing function when terminating.


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

Установка и Выпуская Процедуры Захвата



Вы можете установить рычажную процедуру вызывая функцию SetWindowsHookEx и определяя тип рычажного вызова процедуры, должна процедура быть связана всей резьбой или с конкретной резьбой, и указателем в процедуру точки входа.

Вы должны установить глобальную рычажную процедуру в DLL выделять из приложения, устанавливающего рычажную процедуру. Устанавливающее приложение должно имело ручку модуля DLL прежде, чем оно может установить рычажную процедуру. Функция LoadLibrary, когда дано имя DLL, было возвращано ручка модуля DLL. После того, как у вас есть ручка, Вы можете назвать функцию GetProcAddress, чтобы извлекать адрес рычажной процедуры. Наконец, Вы используете SetWindowsHookEx, чтобы устанавливать рычажный адрес процедуры в подходящей рычажной цепи. SetWindowsHookEx ПЕРЕДАЕТ модульную ручку, указатель в захват-процедуру точки входа, и 0 для идентификатора резьбы, указывая, что рычажная процедура должна быть связана всей резьбой в системе. Эта последовательность показана в следующем примере.

HOOKPROC hkprcSysMsg;
статический HINSTANCE hinstDLL;
статический HHOOK hhookSysMsg;

hinstDLL = LoadLibrary((LPCTSTR) "c:\\windows\\sysmsg.dll");
hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "SysMessageProc");
hhookSysMsg = SetWindowsHookEx(WH_SYSMSGFILTER, hkprcSysMsg, hinstDLL, 0);


Вы можете выпустить заправлять-специфическую рычажную процедуру (удалите свой адрес из рычажной цепи) вызывая функцию UnhookWindowsHookEx, определяющую, что ручка рычажной процедуры выпускает. Выпустите рычажную процедуру как только ваше приложение больше не нужно это.
Вы можете выпустить глобальную рычажную процедуру используя UnhookWindowsHookEx, но эта функция не освобождает DLL, содержащее рычажную процедуру. Дело в том, что глобальные рычажные процедуры приглашены контекст процесса каждого приложения в система, вызывающего подразумевающийся вызов в функцию LoadLibrary для всех тех процессов. Поскольку вызов в функцию FreeLibrary не может быть сделан для другого процесса, есть затем ни за что, чтобы освобождать DLL. Окно в конечном счете освобождает DLL в конце концов процессы явно связанные на DLL иметь или завершено или было названо FreeLibrary и все процессы, которые были названы рычажная процедура продолжила обработку за пределами DLL.

Альтернативный метод для установки глобальной рычажной процедуры должен обеспечить установку функции в DLL, вместе с рычажной процедурой. С этим методом, устанавливающее приложение не нужно ручка модуля DLL. Связываясь с DLL, приложение получает доступ к установке функции. Установка функции может поставить модульную ручку DLL и другие детали на вызове на SetWindowsHookEx. DLL Может также содержать функцию, которая выпускает глобальную рычажную процедуру; приложение может назвать это рычажное освобождение функции при завершении.


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz