N0xus
N0xus

Reputation: 2724

Detecting a left button mouse click Winform

What I'm trying to do is get my winform to display a debug line when ever I click in my winform. However, when I do, nothing happens. I know how to get a button / other click event to happen. But what I need is to be able to click anywhere within my winform.

I've googled this for the past hour but can't see what I'm doing wrong. As far as I'm aware, this code should be correct in detecting a mouse click. This method is held withing the form1.cs class:

private void mouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
        Trace.WriteLine("Mouse clicked");
}

I've tried setting brake points, but these don't get triggered either. What is it I'm doing wrong?

Sorry for the stupidly newbie question, but I am very new to winform programming.

Upvotes: 3

Views: 61820

Answers (4)

user1632861
user1632861

Reputation:

The method itself is correct. I think your actual problem is: you haven't added this method to MouseClick events.

In C# – and most other languages too – event is handled by an event handler. Windows forms and controls have events for all the events happening in your controls, such as OnClick or OnResize. You can append methods to these events, and the methods will automatically get called when the actual event happens. Simply add the following line to your form's constructor, Form_Load-method, InitializeComponent-method, or such:

this.MouseClick += mouseClick;

Now when ever MouseClick event happens, your method mouseClick will be called automatically.

Upvotes: 4

Jason
Jason

Reputation: 6926

Using the editor built-in to Visual Studio:

enter image description here

  1. Go to the properties window (if you don't see it, press Alt + Enter).
  2. Select the events icon (looks like lightning).
  3. Double-click on the empty ComboBox to the right of Click.
  4. You'll be taken to an empty method where you can put your code.

Upvotes: 9

ColinE
ColinE

Reputation: 70160

I would recommend reading Events C# Programming Guide. You need to add an event handler like so:

form1.MouseClick += mouseClick;

Upvotes: 3

codeteq
codeteq

Reputation: 1532

How to add the EventHandler:

public Form1()
{
    InitializeComponent();
    // This line should you place in the InitializeComponent() method.
    this.MouseClick += mouseClick;
}

Upvotes: 9

Related Questions