How to capture mouse windows messages out of the application?

折月煮酒 提交于 2019-12-13 23:58:50

问题


First of all sorry 'cause maybe this could be a too localized question for C# but anyways I didn't find info about this for VB.NET and I don't understand in a good level C# code.

Basically I need to capture/process some mouse messages out of the application.

How I could do it?

This is just a code example of what I need to reproduce but outside the application:

Protected Overrides Sub WndProc(ByRef m As Message)

    Select Case m.Msg

        Case &H200 ' WM_MOUSEMOVE
            MsgBox("Mouse Move")

        Case &H201 ' WM_LBUTTONDOWN
            MsgBox("Left Button Down")

        Case &H202 ' WM_LBUTTONUP 
            MsgBox("Left Button Up")

        Case Else
            MyBase.WndProc(m)

    End Select

End Sub

The main idea is to press a button that will hide the application to let the user selects a region over the screen and there is where I need to capture those windows messages to know when I need to start/end the region selection.


回答1:


There are two ways to do this.

  1. Using global hooks (Google it) I do not recommend.

  2. Making ur winform transparent.

U need set transparent color of ur winform as the background control color. To make the form unfocusable u need add this code to ur message handler

if (m.Msg == WM_MOUSEACTIVATE)
{
    m.Result = new IntPtr(MA_NOACTIVATE);
    return;
}  

if u want to receive left-click message just add this code before MouseActivate massage.

if (m.Msg == WM_LBUTTONDOWN)
{
} 

Complete Example

namespace
{
    public partial class XXXXXForm : Form
    {
        private const int WM_MOUSEACTIVATE = 0x21;
        private const int WM_LBUTTONDOWN = 0x0201;
        private const int MK_LBUTTON = 0x0001;
        private const int MA_NOACTIVATE = 3;

        public ClockForm()
        {
            InitializeComponent();

            this.DoubleBuffered = true;
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.None;
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.TransparencyKey = this.BackColor;

        }


        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private extern static int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        private const int WM_SYSCOMMAND = 0x112;
        private const int SC_MOVE = 0xF010;
        private const int HTCAPTION = 0x0002;


        protected override void WndProc(ref Message m)
        {

            if (m.Msg == WM_LBUTTONDOWN)
            {
...
            }
            else if (m.Msg == WM_MOUSEACTIVATE)
            {
                m.Result = new IntPtr(MA_NOACTIVATE);
                return;
            }
            base.WndProc(ref m);

        }

        protected override bool ShowWithoutActivation
        {
            get
            {
                return false;
            }
        }

        private void Form_Paint(object sender, PaintEventArgs e)
        {

        }

    }
}



回答2:


Firstly, im not quite sure of your question, since you ask how to receive windows messages to capture an area. But from what i understand here, you dont even need windows messages to capture an area on the screen.

This is a small example, its a bit buggy but check it out.

[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("user32.dll")]
static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase);
Rectangle rect;
bool drawmode = false;
Point startLoc;
Point CurrentLoc;

private void button1_Click(object sender, EventArgs e)
{
    if (!drawmode)
    {
        WindowState = FormWindowState.Maximized;
        Opacity = 0.01;
        drawmode = true;
    }
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        CurrentLoc = Cursor.Position;
        IntPtr desktopPtr = GetDC(IntPtr.Zero);
        Graphics g = Graphics.FromHdc(desktopPtr);

        InvalidateRect(IntPtr.Zero, IntPtr.Zero, true);
        rect = new Rectangle(startLoc.X, startLoc.Y, CurrentLoc.X - startLoc.X, CurrentLoc.Y - startLoc.Y);
        g.DrawRectangle(Pens.Red, rect);

        g.Dispose();
        ReleaseDC(IntPtr.Zero, desktopPtr);
    }
    else
    {
        startLoc = Cursor.Position;
    }
}

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    if (drawmode)
    {
        WindowState = FormWindowState.Normal;
        Opacity = 1;
        drawmode = false;
        // do somthing with rect after selection
    }
}

I dont think this is what you are looking for, but im sure this could help someone down the line.




回答3:


I've found here a generic usage mouse hook that applies to all my needs

The code (needs XML documentation and also cleaning unnecessary instructions for my case but it's just to show it):

EDIT:

Code updated.

#Region " Imports "

Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.Reflection

#End Region

''' <summary>
''' Class MouseHook.
''' </summary>
Public Class MouseHook

#Region " WinAPI "

#Region " Methods "

    ''' <summary>
    ''' Passes the hook information to the next hook procedure in the current hook chain. 
    ''' A hook procedure can call this function either before or after processing the hook information.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="idHook">
    ''' This parameter is ignored.
    ''' </param>
    ''' <param name="nCode">
    ''' The hook code passed to the current hook procedure. 
    ''' The next hook procedure uses this code to determine how to process the hook information.
    ''' </param>
    ''' <param name="wParam">
    ''' The wParam value passed to the current hook procedure. 
    ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
    ''' </param>
    ''' <param name="lParam">
    ''' The lParam value passed to the current hook procedure. 
    ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
    ''' </param>
    ''' <returns>
    ''' This value is returned by the next hook procedure in the chain. 
    ''' The current hook procedure must also return this value. 
    ''' The meaning of the return value depends on the hook type. 
    ''' For more information, see the descriptions of the individual hook procedures.
    ''' </returns>
    <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
    Private Shared Function CallNextHookEx(
           ByVal idHook As Integer,
           ByVal nCode As Integer,
           ByVal wParam As Integer,
           ByVal lParam As MSLLHOOKSTRUCT
    ) As Integer
    End Function

    ''' <summary>
    ''' Installs an application-defined hook procedure into a hook chain. 
    ''' You would install a hook procedure to monitor the system for certain types of events. 
    ''' These events are associated either with a specific thread 
    ''' or with all threads in the same desktop as the calling thread.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="idHook">
    ''' The type of hook procedure to be installed.
    ''' </param>
    ''' <param name="lpfn">
    ''' A pointer to the hook procedure. 
    ''' If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, 
    ''' the lpfn parameter must point to a hook procedure in a DLL. 
    ''' Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
    ''' </param>
    ''' <param name="hInstance">
    ''' A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. 
    ''' The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by 
    ''' the current process and if the hook procedure is within the code associated with the current process.
    ''' </param>
    ''' <param name="threadId">
    ''' The identifier of the thread with which the hook procedure is to be associated. 
    ''' For desktop apps, if this parameter is zero, the hook procedure is associated 
    ''' with all existing threads running in the same desktop as the calling thread. 
    ''' </param>
    ''' <returns>
    ''' If the function succeeds, the return value is the handle to the hook procedure.
    ''' If the function fails, the return value is NULL.
    ''' </returns>
    <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
    Private Shared Function SetWindowsHookEx(
           ByVal idHook As HookType,
           ByVal lpfn As MouseProcDelegate,
           ByVal hInstance As IntPtr,
           ByVal threadId As Integer
    ) As Integer
    End Function

    ''' <summary>
    ''' Removes a hook procedure installed in a hook chain by the 'SetWindowsHookEx' function.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644993%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="idHook">
    ''' A handle to the hook to be removed. 
    ''' This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
    ''' </param>
    ''' <returns>
    ''' If the function succeeds, the return value is nonzero.
    ''' If the function fails, the return value is zero.
    ''' </returns>
    <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
    Private Shared Function UnhookWindowsHookEx(
           ByVal idHook As Integer
    ) As Boolean
    End Function

#End Region

#Region " Enums "

    ''' <summary>
    ''' Indicates a type of Hook procedure to be installed.
    ''' </summary>
    <Description("Enum used in 'idHook' parameter of 'SetWindowsHookEx' function")>
    Private Enum HookType As Integer

        ' **************************************
        ' This enumeration is partially defined.
        ' **************************************

        ''' <summary>
        ''' Installs a hook procedure that monitors low-level mouse input events. 
        ''' For more information, see the LowLevelMouseProc hook procedure.
        ''' </summary>
        WH_MOUSE_LL = 14

    End Enum

#End Region

#Region " Structures "

    ''' <summary>
    ''' Contains information about a low-level mouse input event.
    ''' </summary>
    <Description("Structure used in 'lParam' parameter of 'CallNextHookEx' function")>
    Private Structure MSLLHOOKSTRUCT

        ''' <summary>
        ''' The ptThe x- and y-coordinates of the cursor, in screen coordinates.
        ''' </summary>
        Public pt As Point

        ''' <summary>
        ''' If the message is 'WM_MOUSEWHEEL', the high-order word of this member is the wheel delta. 
        ''' The low-order word is reserved. 
        ''' A positive value indicates that the wheel was rotated forward, away from the user; 
        ''' a negative value indicates that the wheel was rotated backward, toward the user. 
        ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
        ''' </summary>
        Public mouseData As Integer

        ''' <summary>
        ''' The event-injected flag.
        ''' </summary>
        Public flags As Integer

        ''' <summary>
        ''' The time stamp for this message. 
        ''' </summary>
        Public time As Integer

        ''' <summary>
        ''' Additional information associated with the message.
        ''' </summary>
        Public dwExtraInfo As Integer

    End Structure

#End Region

#End Region

#Region " Variables "

    ''' <summary>
    ''' 
    ''' </summary>
    Private MouseHook As Integer

#End Region

#Region " Delegates "

    ''' <summary>
    ''' Delegate MouseProcDelegate
    ''' </summary>
    ''' <returns>System.Int32.</returns>
    Private Delegate Function MouseProcDelegate(
            ByVal nCode As Integer,
            ByVal wParam As Integer,
            ByRef lParam As MSLLHOOKSTRUCT
    ) As Integer

    ''' <summary>
    ''' 
    ''' </summary>
    Private MouseHookDelegate As MouseProcDelegate

#End Region

#Region " Enums "

    ''' <summary>
    ''' Indicates a Windows Message related to a mouse events.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ff468877%28v=vs.85%29.aspx
    ''' </summary>
    Private Enum MouseWindowsMessages As Integer

        ''' <summary>
        ''' Posted to a window when the cursor moves. 
        ''' If the mouse is not captured, the message is posted to the window that contains the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MOUSEMOVE = &H200

        ''' <summary>
        ''' Posted when the user presses the left mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONDOWN = &H201

        ''' <summary>
        ''' Posted when the user releases the left mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONUP = &H202

        ''' <summary>
        ''' Posted when the user double-clicks the left mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONDBLCLK = &H203

        ''' <summary>
        ''' Posted when the user presses the right mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONDOWN = &H204

        ''' <summary>
        ''' Posted when the user releases the right mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONUP = &H205

        ''' <summary>
        ''' Posted when the user double-clicks the right mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONDBLCLK = &H206

        ''' <summary>
        ''' Posted when the user presses the middle mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONDOWN = &H207

        ''' <summary>
        ''' Posted when the user releases the middle mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONUP = &H208

        ''' <summary>
        ''' Posted when the user double-clicks the middle mouse button while the cursor is in the client area of a window. 
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor. 
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONDBLCLK = &H209

        ''' <summary>
        ''' Sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated. 
        ''' The DefWindowProc function propagates the message to the window's parent. 
        ''' There should be no internal forwarding of the message, 
        ''' since DefWindowProc propagates it up the parent chain until it finds a window that processes it.
        ''' </summary>
        WM_MOUSEWHEEL = &H20A

    End Enum

    ''' <summary>
    ''' Indicates the whell direction of the mouse.
    ''' </summary>
    Public Enum WheelDirection

        ''' <summary>
        ''' The wheel is moved up.
        ''' </summary>
        WheelUp

        ''' <summary>
        ''' The wheel is moved down.
        ''' </summary>
        WheelDown

    End Enum

#End Region

#Region " Events "

    ''' <summary>
    ''' Occurs when the mouse moves.
    ''' </summary>
    Public Event MouseMove(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is pressed.
    ''' </summary>
    Public Event MouseLeftDown(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is released.
    ''' </summary>
    Public Event MouseLeftUp(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is double-clicked.
    ''' </summary>
    Public Event MouseLeftDoubleClick(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is pressed.
    ''' </summary>
    Public Event MouseRightDown(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is released.
    ''' </summary>
    Public Event MouseRightUp(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is double-clicked.
    ''' </summary>
    Public Event MouseRightDoubleClick(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is pressed.
    ''' </summary>
    Public Event MouseMiddleDown(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is released.
    ''' </summary>
    Public Event MouseMiddleUp(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is double-clicked.
    ''' </summary>
    Public Event MouseMiddleDoubleClick(ByVal ptLocat As Point)

    ''' <summary>
    ''' Occurs when [mouse move].
    ''' </summary>
    Public Event MouseWheel(ByVal ptLocat As Point,
                            ByVal Direction As WheelDirection)

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of this class.
    ''' </summary>
    Public Sub New()

        MouseHookDelegate = New MouseProcDelegate(AddressOf MouseProc)

        MouseHook = SetWindowsHookEx(HookType.WH_MOUSE_LL,
                                     MouseHookDelegate,
                                     Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
    End Sub

#End Region

#Region " Protected Methods "

    ''' <summary>
    ''' Allows an object to try to free resources 
    ''' and perform other cleanup operations before it is reclaimed by garbage collection.
    ''' </summary>
    Protected Overrides Sub Finalize()

        UnhookWindowsHookEx(MouseHook)
        MyBase.Finalize()

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Processes the mouse windows messages and raises it's corresponding events.
    ''' </summary>
    ''' <returns>System.Int32.</returns>
    Private Function MouseProc(ByVal nCode As Integer,
                               ByVal wParam As Integer,
                               ByRef lParam As MSLLHOOKSTRUCT
    ) As Integer

        If nCode = 0 Then

            Select Case wParam

                Case MouseWindowsMessages.WM_MOUSEMOVE
                    RaiseEvent MouseMove(lParam.pt)

                Case MouseWindowsMessages.WM_LBUTTONDOWN
                    RaiseEvent MouseLeftDown(lParam.pt)

                Case MouseWindowsMessages.WM_LBUTTONUP
                    RaiseEvent MouseLeftUp(lParam.pt)

                Case MouseWindowsMessages.WM_LBUTTONDBLCLK
                    RaiseEvent MouseLeftDoubleClick(lParam.pt)

                Case MouseWindowsMessages.WM_RBUTTONDOWN
                    RaiseEvent MouseRightDown(lParam.pt)

                Case MouseWindowsMessages.WM_RBUTTONUP
                    RaiseEvent MouseRightUp(lParam.pt)

                Case MouseWindowsMessages.WM_RBUTTONDBLCLK
                    RaiseEvent MouseRightDoubleClick(lParam.pt)

                Case MouseWindowsMessages.WM_MBUTTONDOWN
                    RaiseEvent MouseMiddleDown(lParam.pt)

                Case MouseWindowsMessages.WM_MBUTTONUP
                    RaiseEvent MouseMiddleUp(lParam.pt)

                Case MouseWindowsMessages.WM_MBUTTONDBLCLK
                    RaiseEvent MouseMiddleDoubleClick(lParam.pt)

                Case MouseWindowsMessages.WM_MOUSEWHEEL
                    Dim wDirection As WheelDirection
                    If lParam.mouseData < 0 Then
                        wDirection = WheelDirection.WheelDown
                    Else
                        wDirection = WheelDirection.WheelUp
                    End If
                    RaiseEvent MouseWheel(lParam.pt, wDirection)

            End Select

        End If

        Return CallNextHookEx(MouseHook, nCode, wParam, lParam)

    End Function

#End Region

End Class

Example usage:

Public Class Form1


Private WithEvents mHook As New MouseHook

Private Sub mHook_Mouse_Left_Down(ByVal ptLocat As System.Drawing.Point) Handles mHook.Mouse_Left_Down
    MsgBox("Mouse Left Down At: (" & ptLocat.X & "," & ptLocat.Y & ")")
End Sub

Private Sub mHook_Mouse_Left_Up(ByVal ptLocat As System.Drawing.Point) Handles mHook.Mouse_Left_Up
    MsgBox("Mouse Left Up At: (" & ptLocat.X & "," & ptLocat.Y & ")")
End Sub

Private Sub mHook_Mouse_Move(ByVal ptLocat As System.Drawing.Point) Handles mHook.Mouse_Move
    'Will be called every time the mouse moves
End Sub

End Class


来源:https://stackoverflow.com/questions/23626869/how-to-capture-mouse-windows-messages-out-of-the-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!