如何处理鼠标事件

时间:2009-10-04 01:02:55

标签: c#

我想在广场内点击,然后会出现“X”,但我不确定要在Form1_MouseDownForm1_PaintForm1_MouseUp事件中放置什么。我如何实现这个是C#?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VTest
{
    public partial class Form1 : Form
    {
        Rectangle rect; // single rect
        int sqsize, n;
        int margin;

        public Form1()
        {
            n = 3;
            margin = 25;
            sqsize = 50;
            rect = new Rectangle(10, 10, 150, 150);
            InitializeComponent();
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            // what goes here?
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // what goes here?
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            // what goes here?
        }

        // ...

4 个答案:

答案 0 :(得分:6)

在MouseDown事件中,确定是否在矩形内发生了点击很容易:

if (rect.Contains(e.Location))
{
    // the user has clicked inside your rectangle
}

在表单上绘制“X”也很容易:

Graphics g = this.CreateGraphics();
g.DrawString("X", this.Font, SystemBrushes.WindowText,
    (float)e.X, (float)e.Y);

然而,在这种情况下,“X”将不会持久,这意味着如果您在表单上拖动另一个表单然后将其移走,则“X”将不再存在。要绘制持久性“X”,请创建一个表单级的Point变量,如下所示:

private Point? _Xlocation = null;

如果用户点击了Rectangle:

,请使用MouseDown事件设置此变量
if (rect.Contains(e.Location))
{
    _Xlocation = e.Location;
    this.Invalidate(); // this will fire the Paint event
}

然后,在表单的Paint事件中,绘制“X”:

if (_Xlocation != null)
{
    e.Graphics.DrawString("X", this.Font, SystemBrushes.WindowText,
        (float)e.X, (float)e.Y);
}
else
{
    e.Graphics.Clear(this.BackColor);
}

如果您希望当用户放开鼠标按钮时“X”消失,只需将此代码放入MouseUp事件中:

_Xlocation = null;
this.Invalidate();

你可以根据自己的喜好变得更加复杂。使用此代码,“X”将在您单击表单的任何位置的下方和右侧绘制。如果您希望“X”在单击位置居中,您可以使用Graphics对象的MeasureString方法来确定“X”的高度和宽度,并相应地偏移DrawString位置

答案 1 :(得分:0)

您不需要mousedown和mouseup事件处理程序。

选择一个做出反应,我倾向于对MouseDown事件做出反应。

但是,当你想要查看MouseEventArgs属性时,你应该能够确定你是否在广场内。

您可能想要致电:

System.Diagnostics.Debug.WriteLine(...)

使用MouseEventArgs中的x和y属性,这样您就可以看到鼠标点击的位置,并确定您何时在广场上。

一旦你在那里,你就可以画出X。

您可能想要编写一个函数来绘制X并通过在300,300处绘制X来测试它,这样您就可以在尝试使用MouseDown时确保它看起来像。

答案 2 :(得分:0)

更新:我喜欢MusiGenesis演示的Rectangle.contains(location)方法。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DemoWindowApp
{
    public partial class frmDemo : Form
    {
        Rectangle rec;
        public frmDemo()
        {
            InitializeComponent();
        }

        private void frmDemo_Load(object sender, EventArgs e)
        {
            rec = new Rectangle(150,100,100,100);
        }

        private void frmDemo_Paint(object sender, PaintEventArgs e)
        {   
            Pen p = new Pen(Color.Blue);
            Graphics g = e.Graphics;

            g.DrawRectangle(p,rec);
        }

        private void frmDemo_MouseMove(object sender, MouseEventArgs e)
        {
            if(rec.Contains(e.Location))
            {
                Cursor = Cursors.Cross;
            }else
            {
                Cursor = Cursors.Default;
            }
        }

        private void frmDemo_MouseDown(object sender, MouseEventArgs e)
        {   
            if(rec.Contains(e.Location))
            {
                //mouse position adjust for window postion and border size.
                //you may have to adjust the borders depending your
                //windows theme
                int x = MousePosition.X - this.Left -  4;
                int y = MousePosition.Y - this.Top  - 29;

                Graphics g = this.CreateGraphics();
                Pen p = new Pen(Color.Black);
                Point p1 = new Point(x-10,y-10);
                Point p2 = new Point(x+10,y+10);
                Point p3 = new Point(x-10,y+10);
                Point p4 = new Point(x+10,y-10);

                g.DrawLines(p,new Point[]{p1,p2});
                g.DrawLines(p,new Point[]{p3,p4});
            }
        }
    }
}

答案 3 :(得分:0)

请参阅此处的代码:

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

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

        MouseHook mh;

        private void Form1_Load(object sender, EventArgs e)
        {
            mh = new MouseHook();
            mh.SetHook();
            mh.MouseMoveEvent += mh_MouseMoveEvent;
            mh.MouseClickEvent += mh_MouseClickEvent;
            mh.MouseDownEvent += mh_MouseDownEvent;
            mh.MouseUpEvent += mh_MouseUpEvent;
        }
        private void mh_MouseDownEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Press\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Press\n");
            }
        }

        private void mh_MouseUpEvent(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Release\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Release\n");
            }

        }
        private void mh_MouseClickEvent(object sender, MouseEventArgs e)
        {
            //MessageBox.Show(e.X + "-" + e.Y);
            if (e.Button == MouseButtons.Left)
            {
                string sText = "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
                label1.Text = sText;
            }
        }

        private void mh_MouseMoveEvent(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            textBox1.Text = x + "";
            textBox2.Text = y + "";
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            mh.UnHook();
        }

        private void Form1_FormClosed_1(object sender, FormClosedEventArgs e)
        {
            mh.UnHook();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }

    public class Win32Api
    {
        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }
        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
    }

    public class MouseHook
    {
        private Point point;
        private Point Point
        {
            get { return point; }
            set
            {
                if (point != value)
                {
                    point = value;
                    if (MouseMoveEvent != null)
                    {
                        var e = new MouseEventArgs(MouseButtons.None, 0, point.X, point.Y, 0);
                        MouseMoveEvent(this, e);
                    }
                }
            }
        }
        private int hHook;
        private const int WM_MOUSEMOVE = 0x200;
        private const int WM_LBUTTONDOWN = 0x201;
        private const int WM_RBUTTONDOWN = 0x204;
        private const int WM_MBUTTONDOWN = 0x207;
        private const int WM_LBUTTONUP = 0x202;
        private const int WM_RBUTTONUP = 0x205;
        private const int WM_MBUTTONUP = 0x208;
        private const int WM_LBUTTONDBLCLK = 0x203;
        private const int WM_RBUTTONDBLCLK = 0x206;
        private const int WM_MBUTTONDBLCLK = 0x209;
        public const int WH_MOUSE_LL = 14;
        public Win32Api.HookProc hProc;
        public MouseHook()
        {
            this.Point = new Point();
        }
        public int SetHook()
        {
            hProc = new Win32Api.HookProc(MouseHookProc);
            hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0);
            return hHook;
        }
        public void UnHook()
        {
            Win32Api.UnhookWindowsHookEx(hHook);
        }
        private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            Win32Api.MouseHookStruct MyMouseHookStruct = (Win32Api.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.MouseHookStruct));
            if (nCode < 0)
            {
                return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
            }
            else
            {
                if (MouseClickEvent != null)
                {
                    MouseButtons button = MouseButtons.None;
                    int clickCount = 0;
                    switch ((Int32)wParam)
                    {
                        case WM_LBUTTONDOWN:
                            button = MouseButtons.Left;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_RBUTTONDOWN:
                            button = MouseButtons.Right;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_MBUTTONDOWN:
                            button = MouseButtons.Middle;
                            clickCount = 1;
                            MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_LBUTTONUP:
                            button = MouseButtons.Left;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_RBUTTONUP:
                            button = MouseButtons.Right;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                        case WM_MBUTTONUP:
                            button = MouseButtons.Middle;
                            clickCount = 1;
                            MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
                            break;
                    }

                    var e = new MouseEventArgs(button, clickCount, point.X, point.Y, 0);
                    MouseClickEvent(this, e);
                }
                this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y);
                return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
            }
        }

        public delegate void MouseMoveHandler(object sender, MouseEventArgs e);
        public event MouseMoveHandler MouseMoveEvent;

        public delegate void MouseClickHandler(object sender, MouseEventArgs e);
        public event MouseClickHandler MouseClickEvent;

        public delegate void MouseDownHandler(object sender, MouseEventArgs e);
        public event MouseDownHandler MouseDownEvent;

        public delegate void MouseUpHandler(object sender, MouseEventArgs e);
        public event MouseUpHandler MouseUpEvent;

    }
}

在此演示中,您可以检测鼠标的实时位置,并检测mouseup / domn事件。它将在此演示中的richtextbox上显示。

有关鼠标事件的更多教程或下载此演示you can see here.

相关问题