Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Ctrl+Left (mouse button) in MouseDown event handler

When I first press down control key (the left one) and then click the left mouse button, why does the following code gets executed. I am modifying existing code and the below code is already there. I guess no one has tried it before, with control key pressed, it has only been used with left-mouse-clicked and it has always worked for that case. But I want a different code executed when the mouse left key is pressed at the same time that the control key is pressed.

private void treeList1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    TreeList tree = sender as TreeList;

    if (e.Button == MouseButtons.Right && ModifierKeys == Keys.None && tree.State == TreeListState.Regular)
    {
       //the code that is here gets executed 
       MessageBox.Show("I am here");
    }
}

I would highly appreciate any hint or help.

P.S. I would like to add that in the above case when I inspect e.button value it shows that is equal to Right although I pressed the left mouse button and the Ctrl Key. That is a mystery to me.

Dear StackOverflow fellows :I found the problem, since I am using a VM on a MAC I had to disable some Key Mapping on my Virtual Machine preference and now my original code works. Thanks for all your help.

like image 600
user1298925 Avatar asked Feb 18 '13 23:02

user1298925


1 Answers

Keys.None has a value of 0, making it hard to detect when "no key is pressed" when used alone. This:

    void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && (ModifierKeys & Keys.None) == Keys.None)
        {
            MessageBox.Show("No key was held down.");
        }
    }

Will pop a message box whatever the key combination is, as long as the click occurs with the left button.

However, this:

    void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && (ModifierKeys & Keys.Control) == Keys.Control)
        {
            MessageBox.Show("Control key was held down.");
        }
    }

Will only pop a message box when the Control key is held down (and the left mouse button is clicked).

Try reversing your conditions and detect when the Control key is pressed when clicking (instead of detecting when no key is pressed). That being said I'm having a hard time getting the same code to work with Keys.ControlKey or Keys.LControlKey for some reason, so isolating the left control key needs a little more research.

like image 109
Mathieu Guindon Avatar answered Sep 25 '22 06:09

Mathieu Guindon