I'm using the as keyword to "convert" e to a mouse event
Don't do it. Why?
Because if someone uses keyboard (TABs + Enter) or Button.PerformClick call to trigger your button, the conversion will fail and your:
MouseEventArgs mouseArgs = e as MouseEventArgs ;
if (mouseArgs.MouseButton == MouseButton.Left) ...
will lead to NullReferenceException
.
You can't guarantee that EventArgs e
in OnClick
event will be MouseEventArgs. It is just the most common scenario, but not the only one possible.
P.S.: As it has been already pointed by @terribleProgrammer you could use Cursor.Position static property to get the current cursor position in more independent and robust way.
But if the cursor information makes sense only if the button has been triggered by mouse, then you will have just to be careful and handle possible conversion failure:
MouseEventArgs mouseArgs = e as MouseEventArgs ;
if (mouseArgs == null)
{
Logger.Log("mouseArgs is null");
return;
}
if (mouseArgs.MouseButton == MouseButton.Left) ...
EDIT:
There are three main ways to raise the event and three corresponding eventArgs classes:
- Using mouse -
MouseEventArgs
- Using keyboard -
KeyEventArgs
- Using
PerformClick
method - I am not sure, but it will probably be just plain EventArgs
(to verify just raise it in such a way and take a look at e.GetType()).
- Whether there are any other scenarios that will raise it, I don't know. MSDN is of no use for such requests.
P.S.1.: And I want to repeat again - do not assume that e
parameter will be of some specific type. Windows Forms API even does not guarantee that e will contain some concrete useful EventArgs
-derived class.