简体   繁体   中英

Get int of leftclick state with mouse global hook in c#

I'm new to c#/winforms and i wanted to get mouse state as an int to check it in an "if" statement. (For exemple, left click)

So I found a global mouse hook [Here][1], wich works great.

But i don't understand how i can get the mouse state as an int, i searched for a long time on forums and wikis.

I've an error when i create an int in the hookCallback , where the click state is checked (If i understanded as well)

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            MouseHook.Start();
            MouseHook.MouseAction += ne

w EventHandler(Event);
        }

    private void Event(object sender, EventArgs e) { Console.WriteLine("Left mouse click!"); }
}

public static class MouseHook
{
    public static event EventHandler MouseAction = delegate { };

    public static void Start()
    {
        _hookID = SetHook(_proc);


    }
    public static void stop()
    {
        UnhookWindowsHookEx(_hookID);
    }

    private static LowLevelMouseProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    private static IntPtr SetHook(LowLevelMouseProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_MOUSE_LL, proc,
              GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
      int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
        {
            MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
            MouseAction(null, new EventArgs());
           ******** public int LeftClick = 1; *********
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    private const int WH_MOUSE_LL = 14;

    private enum MouseMessages
    {
        WM_LBUTTONDOWN = 0x0201,
        WM_LBUTTONUP = 0x0202,
        WM_MOUSEMOVE = 0x0200,
        WM_MOUSEWHEEL = 0x020A,
        WM_RBUTTONDOWN = 0x0204,
        WM_RBUTTONUP = 0x0205
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct POINT
    {
        public int x;
        public int y;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct MSLLHOOKSTRUCT
    {
        public POINT pt;
        public uint mouseData;
        public uint flags;
        public uint time;
        public IntPtr dwExtraInfo;
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
      LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
      IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);


}

}

Add my class to your project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace Hector.Framework.Utils
{
    public class Peripherals
    {
        public class Mouse
        {
            public static int X
            {
                get => Cursor.Position.X;
            }

            public static int Y
            {
                get => Cursor.Position.Y;
            }

            public static void MoveToPoint(int X, int Y)
            {
                Win32.SetCursorPos(X, Y);
            }

            public static void Hide()
            {
                Cursor.Hide();
            }

            public static void Show()
            {
                Cursor.Show();
            }

            public static bool IsHidden
            {
                get => Cursor.Current == null;
            }

            /// <summary>
            /// ButtonNumber: 0-None 1-Left 2-Middle 3-Right 4-XButton1 5-XButton2
            /// </summary>
            public static bool MouseButtonIsDown(int ButtonNumber)
            {
                bool outValue = false;
                bool isLeft = Control.MouseButtons == MouseButtons.Left;
                bool isRight = Control.MouseButtons == MouseButtons.Right;
                bool isMiddle = Control.MouseButtons == MouseButtons.Middle;
                bool isXButton1 = Control.MouseButtons == MouseButtons.XButton1;
                bool isXButton2 = Control.MouseButtons == MouseButtons.XButton2;

                switch (ButtonNumber)
                {
                    case 0:
                        outValue = false;
                        break;
                    case 1:
                        outValue = isLeft;
                        break;
                    case 2:
                        outValue = isMiddle;
                        break;
                    case 3:
                        outValue = isRight;
                        break;
                    case 4:
                        outValue = isXButton1;
                        break;
                    case 5:
                        outValue = isXButton2;
                        break;
                }

                return outValue;
            }

            /// <summary>
            /// This function is in Alpha Phase
            /// </summary>
            /// <param name="FocusedControl">The control that is scrolled; If the control has no focus, it will be applied automatically</param>
            /// <param name="FontSize">This is used to calculate the number of pixels to move, its default value is 20</param>
            static int delta = 0;
            static int numberOfTextLinesToMove = 0;
            static int numberOfPixelsToMove = 0;
            public static bool GetWheelValues(Control FocusedControl, out int Delta, out int NumberOfTextLinesToMove, out int NumberOfPixelsToMove, int FontSize = 20)
            {
                try
                {
                    if (FocusedControl == null) throw new NullReferenceException("The FocusedControl can not bel null");
                    if (!FocusedControl.Focused) FocusedControl.Focus();
                    FocusedControl.MouseWheel += (object sender, MouseEventArgs e) =>
                    {
                        delta = e.Delta;
                        numberOfTextLinesToMove = e.Delta * SystemInformation.MouseWheelScrollLines / 120;
                        numberOfPixelsToMove = numberOfTextLinesToMove * FontSize;
                    };

                    Delta = delta;
                    NumberOfTextLinesToMove = numberOfTextLinesToMove;
                    NumberOfPixelsToMove = numberOfPixelsToMove;

                    return true;
                }
                catch
                {
                    Delta = 0;
                    NumberOfTextLinesToMove = 0;
                    NumberOfPixelsToMove = numberOfPixelsToMove;

                    return false;
                }
            }

            private class Win32
            {
                [DllImport("User32.Dll")]
                public static extern long SetCursorPos(int x, int y);

                [DllImport("User32.Dll")]
                public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

                [StructLayout(LayoutKind.Sequential)]
                public struct POINT
                {
                    public int x;
                    public int y;
                }
            }
        }
    }
}

Then where you need to check the mouse's status, write the following:

bool MouseLeftButton = Hector.Framework.Utils.Peripherals.Mouse.MouseButtonIsDown(1);

Remember: While selected button is pressed, bool is true, when button released, bool is false

The ButtonNumbers:

  • 0 - None,
  • 1 - Left,
  • 2 - Middle,
  • 3 - Right,
  • 4 - XButton1,
  • 5 - XButton2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM