Intercept all windows messages

Пользовательский перехватчик сообщений Custom Message Interceptor

Данный образец демонстрирует использование модели расширяемости канала. This sample demonstrates the use of the channel extensibility model. В частности, показано, как реализовать пользовательский элемент привязки, который создает фабрики и прослушиватели каналов для перехвата всех входящих и исходящих сообщений в определенной точке стека времени выполнения. In particular, it shows how to implement a custom binding element that creates channel factories and channel listeners to intercept all incoming and outgoing messages at a particular point in the run-time stack. В состав образца входят клиент и сервер, которые демонстрируют использование этих пользовательских фабрик. The sample also includes a client and server that demonstrate the use of these custom factories.

В этом образце служба и клиент являются консольными программами (EXE). In this sample, both the client and the service are console programs (.exe). Как клиент, так и служба используют общую библиотеку (DLL), которая содержит пользовательский элемент привязки и ассоциированные с ним объекты времени выполнения. The client and service both make use of a common library (.dll) that contains the custom binding element and its associated run-time objects.

Процедура настройки и инструкции по построению для данного образца приведены в конце этого раздела. The setup procedure and build instructions for this sample are located at the end of this topic.

Образцы уже могут быть установлены на компьютере. The samples may already be installed on your machine. Перед продолжением проверьте следующий каталог (по умолчанию). Check for the following (default) directory before continuing.

Если этот каталог не существует, перейдите к примерам Windows Communication Foundation (WCF) и Windows Workflow Foundation (WF) для платформа .NET Framework 4 , чтобы скачать все Windows Communication Foundation (WCF) и WF WF примеры. If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and WF WF samples. Этот образец расположен в следующем каталоге. This sample is located in the following directory.

В этом примере описывается рекомендуемая процедура создания пользовательского многоуровневого канала в Windows Communication Foundation (WCF) с помощью платформы Channel и следующих рекомендаций по WCF. The sample describes the recommended procedure for creating a custom layered channel in Windows Communication Foundation (WCF), by using the channel framework and following WCF best practices. Чтобы создать пользовательский многоуровневый канал, выполните следующие действия. The steps to create a custom layered channel are as follows:

Выберите формы канала, которые будут поддерживать фабрика и прослушиватель каналов. Decide which of the channel shapes your channel factory and channel listener will support.

Создайте фабрику и прослушиватель каналов, которые поддерживают выбранную форму канала. Create a channel factory and a channel listener that support your channel shapes.

Присоедините элемент привязки, добавляющий пользовательский многоуровневый канал в стек каналов. Add a binding element that adds the custom layered channel to a channel stack.

Добавьте раздел расширения элементов привязки, чтобы представить новый элемент привязки системе конфигурации. Add a binding element extension section to expose the new binding element to the configuration system.

Формы каналов Channel Shapes

При создании пользовательского многоуровневого канала в первую очередь необходимо решить, какие формы требуются для канала. The first step in writing a custom layered channel is to decide which shapes are required for the channel. Данным инспектором сообщений поддерживается любая форма, поддерживаемая уровнем ниже (например, если уровень ниже может выполнить построение метода IOutputChannel и интерфейса IDuplexSessionChannel, то также предоставляется метод IOutputChannel и интерфейс IDuplexSessionChannel). For our message inspector, we support any shape that the layer below us supports (for example, if the layer below us can build IOutputChannel and IDuplexSessionChannel, then we also expose IOutputChannel and IDuplexSessionChannel).

Читайте также:  Raid disks in windows

Фабрика и прослушиватель каналов Channel Factory and Listener Factory

Следующий шаг создания пользовательского многоуровневого канала — реализация интерфейса IChannelFactory для каналов клиентов и интерфейса IChannelListener для каналов служб. The next step in writing a custom layered channel is to create an implementation of IChannelFactory for client channels and of IChannelListener for service channels.

Эти классы получают внутреннюю фабрику и прослушиватель и делегируют все вызовы внутренней фабрике и прослушивателю, кроме OnCreateChannel и OnAcceptChannel . These classes take an inner factory and listener, and delegate all but the OnCreateChannel and OnAcceptChannel calls to the inner factory and listener.

Добавление элемента привязки Adding a Binding Element

В образце определен пользовательский элемент привязки: InterceptingBindingElement . The sample defines a custom binding element: InterceptingBindingElement . InterceptingBindingElement принимает в ChannelMessageInterceptor качестве входных данных и использует его ChannelMessageInterceptor для обработки сообщений, которые проходят через него. InterceptingBindingElement takes a ChannelMessageInterceptor as an input, and uses this ChannelMessageInterceptor to manipulate messages that pass through it. Только этот класс должен быть открытым. This is the only class that must be public. Фабрика, прослушиватель и каналы — все они могут являться внутренними реализациями открытых интерфейсов времени выполнения. The factory, listener, and channels can all be internal implementations of the public run-time interfaces.

Добавление поддержки конфигурации Adding Configuration Support

Для интеграции с конфигурацией привязки библиотека определяет обработчик раздела конфигурации в качестве раздела расширения элемента привязки. To integrate with binding configuration, the library defines a configuration section handler as a binding element extension section. Файлы конфигурации клиента и сервера должны зарегистрировать расширение элемента привязки в системе конфигурации. The client and server configuration files must register the binding element extension with the configuration system. Реализации, требующие предоставить их элементы привязки в системе конфигурации, могут наследовать от этого класса. Implementers that want to expose their binding element to the configuration system can derive from this class.

Добавление политики Adding Policy

Для интеграции с системой политики InterceptingBindingElement реализует расширение IPolicyExportExtension, чтобы сообщить об участии в создании политики. To integrate with our policy system, InterceptingBindingElement implements IPolicyExportExtension to signal that we should participate in generating policy. Чтобы поддержать импорт политики на созданном клиенте, пользователь может зарегистрировать производный класс InterceptingBindingElementImporter и переопределить CreateMessageInterceptor (), чтобы создать принадлежащий им класс ChannelMessageInterceptor с разрешенной политикой. To support importing policy on a generated client, the user can register a derived class of InterceptingBindingElementImporter and override CreateMessageInterceptor () to generate their policy-enabled ChannelMessageInterceptor class.

Пример: инспектор сообщений, допускающий удаление. Example: Droppable Message Inspector

Включенный в пример образец реализации ChannelMessageInspector удаляет сообщения. Included in the sample is an example implementation of ChannelMessageInspector which drops messages.

Его можно открыть из конфигурации следующим образом: You can access it from configuration as follows:

Клиент и сервер используют заново созданный раздел конфигурации, чтобы добавить пользовательские фабрики в самый нижний уровень принадлежащих им стеков канала времени выполнения (расположенные над транспортным уровнем). The client and server both use this newly created configuration section to insert the custom factories into the lowest-level of their run-time channel stacks (above the transport level).

Клиент использует библиотеку MessageInterceptor , чтобы добавить пользовательский заголовок даже в нумерованные сообщения. The client uses the MessageInterceptor library to add a custom header to even numbered messages. С другой стороны, служба использует библиотеку MessageInterceptor , чтобы удалять любые сообщения, которые не содержат этот специальный заголовок. The service on the other hand uses MessageInterceptor library to drop any messages that do not have this special header.

Клиент должен предоставить результат своей работы после запуска службы и последующего запуска клиента. You should see the following client output after running the service and then the client.

Клиент отправляет отчет службе о 10 различных значениях скорости ветра, но только половина этих значений помечена специальным заголовком. The client reports 10 different wind speeds to the service, but only tags half of them with the special header.

Служба должна предоставить следующие результаты: On the service, you should see the following output:

Читайте также:  Как включить upnp nat pmp windows 10

Настройка, сборка и выполнение образца To set up, build, and run the sample

Установите ASP.NET 4,0 с помощью следующей команды. Install ASP.NET 4.0 using the following command.

Чтобы выполнить сборку решения, следуйте инструкциям в разделе Создание примеров Windows Communication Foundation. To build the solution, follow the instructions in Building the Windows Communication Foundation Samples.

Чтобы запустить пример в конфигурации с одним или несколькими компьютерами, следуйте инструкциям в разделе выполнение примеров Windows Communication Foundation. To run the sample in a single- or cross-machine configuration, follow the instructions in Running the Windows Communication Foundation Samples.

Intercept Windows Messages And Winforms

So going back to the beginning of this issue. I have using System.Windows.Forms to create a text editor. The textbox control by default accepts an event when its contained text is double-clicked and highlights the entire row of text. I wanted to override this behavior with something different. It turns out this requires that I intercept the windows message that kicks off this event and prevent it from ever getting triggered. Here is a link I found on Stackoverflow that explains almost verbatim what I am doing: Is it possible to disable textbox from selecting part of text through double-click

But this explanation is incomplete! Notice that DoubleClickEvent inherits from EventArgs. It should be inheriting from MouseEventArgs. This is because PreviewDoubleClick is going to need information from the windows message about where the screen was clicked. So that’s the task I set off to accomplish: override the doubleclick event but still send it all of the click information from the windows message.

If I set up breakpoints in the code, I begin to see where my information is stored. Message m contains a couple properties, one of which is called LParam. As I understand, this is a pointer to the click information I want to retrieve. But this isn’t C++. I cannot just dereference the pointer. .NET conveniently provides the Message.GetLParam method to help me out. I am having trouble getting this method to work.

Here is my code:

As you can see it, looks a lot like the sample. The crazy casting I did to get it to compile on this line DoubleClickEventArgs e = (DoubleClickEventArgs) m.GetLParam(typeof(MouseEventArgs)); is obviously causing the crash. We get the error: No parameterless constructor defined for this object.

That makes sense. DoubleCLickEventArgs do require parameters to be created. But the parameters are defined by the lParam pointer. Can anyone give me a little guidance here? I’m struggling.

Global hooks to intercept windows messages

#1

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    It has been a long time since i’ve posted something interesting,so i decided to do so.
    From what i understand,people are very interested in windows hooks and their great functionality.I’ve made an example for low level keyboard hooks some time ago here (http://www.rohitab.c. good-keylogger/) and i see a lot of interest in the idea.

    Someone here asked if it can be possible to intercept something else,like messages passed in windows apps procedures,like WM_CREATE,WM_CLOSE,WM_COMMAND,etc.

    The answer is yes,it can be done.But with global hooks.This is done using a dll that contains the proper hook procedure and an executable,of course that loads and shares this resource with every other windows application that will be interogated.

    Ok so no more talk,i will explain for everyone that doesn’t understand something at the time.For now,the source code:

    And the exe that implements it:

    This will intercept any WM_CLOSE message in all applications and will show a message box each time,with the closed process name in the title!

    Edited by Athenian, 14 November 2014 — 05:54 PM.

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #2

  • Members
  • 399 posts
  • Reputation: 175
    • Gender: Male
    • Location: Hungary
    • Interests: C++, x86asm, Reverse Engineering
    • Coding: AutoIt, C/C++

    Could you explain me whatthose pragmas are, and why did you put that there?

    I’ve just never heard of them

    Hmm, as I read, it puts data into a different section, but why? Is there any reason, or just for fun?

    Читайте также:  У кого какие фаерволы windows

    Edited by Unc3nZureD, 14 November 2014 — 10:10 PM.

    #3

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    Sorry for that.They ware from another project,so you can remove them.There is no need for them!

    You can store variables in your own defined section.For example:

    will put i to .rohitab section in the PE file.

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #4

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    But i dont recomand it.What i can suggest you,if you want to force the linker to add some variables into a certain section,is this:

    This will create a section with the name rohitab and with read,write and execute attributes.With __declspec(allocate(«.rohitab»)),we specify that we want the next line to be added to that section,in this case the ‘w’ character.Use PE Explorer to look into the sections of the executable or dll and you will see the result!

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #5

  • Members
  • 399 posts
  • Reputation: 175
    • Gender: Male
    • Location: Hungary
    • Interests: C++, x86asm, Reverse Engineering
    • Coding: AutoIt, C/C++

    Only the next line will be added, or all of the others coming after this? (Sorry I can’t test it currently)

    #6

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #7

  • Members
  • 60 posts
  • Reputation: 8
    • Gender: Male
    • Location: Las Vegas, NV
    • Interests: Coding
    • Coding: C++, PHP

    Suppose instead of «if (data->message == WM_CLOSE)» we’d have «if (data->message == WM_SETTEXT)»:

    Is there any way to get the lParam value from data->lparam ?

    Sometimes applications set text on windows with WM_SETTEXT, anyway to get this text ?

    #8

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    Yes my friend!
    It can be done.Just modify the dll:

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #9

  • Members
  • 395 posts
  • Reputation: 143
    • Gender: Male
    • Location: Mars
    • Interests: too many!
    • Coding: Python,C,asm,java

    ​this and the other hook tuts should be put together into one complete tutorial on windows hooks. like the one RosDevil did on dll injection.

    Edited by Null_00, 08 August 2015 — 10:22 AM.

    Shadow Network

    Shadow Society

    #10

  • Members
  • 1106 posts
  • Reputation: 573
    • Gender: Male
    • Location: Romania
    • Interests: Help and learn!
    • Coding: C/C++,PHP,ASM x86,MySql,HTML5 + CSS3,JAVA,jQuery/javascript,COM
      Hardware engineer,Network architect

    @null
    Copy all source codes you think are the best on rohitab (all time) and put them into a huge archive.
    Maybe one day rohitab wouldnt exist anymore and some people may seek knowledge.

    If you got the time ofcourse!

    mov problems,hell
    sub me,pain

    add me,love
    inc pleasure
    inc adrenaline

    push limits
    call hopeForAbetterTomorrow

    #11

  • Members
  • 60 posts
  • Reputation: 8
    • Gender: Male
    • Location: Las Vegas, NV
    • Interests: Coding
    • Coding: C++, PHP

    Screenshot:

    Edited by eclessiastes, 29 August 2015 — 06:08 AM.

    #12

  • Probation
  • 1 posts
  • Reputation: 0

    Oh. I am so happy, because I tried you code and it worked. Recently I want to get gesture information from Surface pro 3(like zoom), I think I need to use the hook :WH_GETMESSAGE. So I just replaced WH_CALLWNDPROC with WH_GETMESSAGE in you code. The hook can be installed, but the function in dll:

    extern «C» __declspec(dllexport) LRESULT WINAPI procedure(int nCode, WPARAM wParam, LPARAM lParam)

    can not be called.

    So my friend,do you have any idea why it happened? I have been confused by this topic for almost one month! Waiting for your suggestion. Thank you so much!

  • Оцените статью