David Eaton
David Eaton

Reputation: 564

C# Detecting a Click in WndProc and calling a function after click happened

I am trying to detect a click and preform calling a function only after the click actually happened.

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m) {
    //Detect a Click
    if (m.Msg == 0x210 && m.WParam.ToInt32() == 513){
        lastClick = DateTime.Now;
        clickedHappened();
        Debug.Print("Click Detected!");
    }

    base.WndProc(ref m);

}

private void clickedHappened(){
    MessageBox.Show("Click Already Happened");
}

I think that WndProc happens way before the actual click takes place.
I was wondering if there was a way to solve this with out using a timer? or sleep(400);

The only solution I can come up with is using a timer, but I want to get rid of some of my existing timers. It seems that the click actually happens 200 - 350 ms after it was detected in WndProc.

Upvotes: 3

Views: 12795

Answers (2)

bizzehdee
bizzehdee

Reputation: 21003

WndProc is short for Window Procedure, its the procedure that handles everything for the window, drawing, mouse capture, keyboard capture, resizing...

There are also several ways you can capture the mouse for varying results

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
    switch(m.Msg)
    {
         case 0x201:
           //left button down
           break;
          case 0x202:
           clickedHappened(); //left button up, ie. a click
           break;
         case 0x203:
           //left button double click
           break;
    }

    base.WndProc(ref m);
}

The thing is, windows forms in C# already handles all of these for you and from the WndProc, fires events there is no real need to handle WndProc yourself for this type of thing.

For a full list of mouse notification messages, see MSDN: Mouse Input Notifications and for a list of all wndproc messages, see MSDN System Defined Messages

Upvotes: 4

SergeyIL
SergeyIL

Reputation: 595

Probably, you can handle WM_LBUTTONUP message that occured after click. You can do it like this:

const int WM_LBUTTONUP = 0x202;

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_LBUTTONUP)
    {               
        clickedHappened();
    }

    base.WndProc(ref m);
}

Upvotes: 0

Related Questions