Can't fire MouseWheel event in C# Windows Forms - c#

First off, the mousewheel event is not listed in Visual Studio 2008's events pane which is very annoying.
I found the correct format online though, and wrote this into my code:
private void Form1_MouseWheel(object sender, MouseEventArgs e)
{
Debug.WriteLine("Foo");
}
...from which I'm getting no response when the mousewheel is rotated.
I'm doing this in my code's main class area, and the designer contains only the one form/window/whatever so the mouse isn't losing focus.
namespace BlahBlah
{
public partial class Form1 : Form
{
And by contrast, I have this method right above the mousewheel one and it works fine:
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
Debug.WriteLine("Foo");
}
If I had to guess, I'm thinking I'm not correctly linking the code to the form (aka: all the stuff that visual studio would do for me if I added this event through the designer's events panel). But I could be wrong or just be making some silly error.
Can you help me get ANY kind of response when the mouse wheel is rotated? Thanks!

The mousewheel event needs to be set up.
Add this to Form1's constructor (After InitalizeComponents();)
this.MouseWheel+= new MouseEventHandler(Form1_MouseWheel);

I don't have enough reputation to respond with a comment, but the answer to your side question is that the delegates do need to be setup. However when you create one by double clicking it in the properties pane the code is automatically generated and placed in the *.designer.cs file in the InitializeComponent method.

It's best in this case to override the OnMouseWheel member function rather than register to the event. For example:
public class MyFrm : Form
{
protected override void OnMouseWheel(MouseEventArgs e)
{
/*Handle the mouse wheel here*/
base.OnMouseWheel(e);
}
}

I don't know how to subscribe to that particular event but you can override the appropriate method on the form, instead.

Related

MouseMove Event, no decent examples

Can't get my head around this, there are no decent examples on how to setup an event listener for a mouse move event.
I can find references like this and this but that doesn't really help...
How can I do something like this:
public event MouseEventHandler(object sender, MouseEventArgs e)
{
//Manage mouse move event
//Get X, Y position of mouse ect...
}
Edit:
I'm getting two errors:
A static readonly field cannot be assigned to (except in a static
constructor or a variable initializer)
Operator '+=' cannot be applied to operands of type 'RoutedEvent' and
'method group'
These errors are on this line: Mouse.MouseMoveEvent += mouseEventHandler.
public MainWindow()
{
InitializeComponent();
Mouse.MouseMoveEvent += mouseEventHandler;
}
public void mouseEventHandler(object sender, MouseEventArgs e)
{
Point mousePosition = e.GetPosition(this);
}
Simply attach an event handler to the MouseMove event of any UIElement.
For example, you could add it to a Window in the code-behind like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.MouseMove += Window_MouseMove;
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
Console.WriteLine("Mouse moved");
}
}
The alternative to attaching the event handler in C# in code-behind is to set it using XAML, e.g. for above window, it could be like this:
<Window …
MouseMove="Window_MouseMove">
Note that you still need to declare the Window_MouseMove method in the code-behind.
EDIT:
If you are using Forms, you probably want to use:
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousemove(v=vs.110).aspx
Like:
System.Windows.Forms.MouseMove += MouseEventHandler
Take in mind you need a instance of Forms, and use it directly like:
this.MouseMove += MouseEventHandler
Because of the InitializeComponent() function in your constructor I guess you are using Winforms using the designer in visual studio
Apart from the correct answers others gave I want to point out to you that subscribing to events in visual studio is really easy in the designer.
The designer is the part where you draw the form, add all the buttons, text boxes etc.
To add an event handler for your mouse move (or for any event that any component in your form might raise), do the following:
Select the component that should react on the your move move, for instance a button, or the form you are designing
Go to the properties window of this component (there are a lot of possibilities of how to do this, one of it is via menu view - properties
In the properties window you see a lightning flash sign. If you click on it, you see a list of most events the component can generate
One of these events is the mousemove. Type a function name, or double click on the event to generate a default name.
The event handler is generated with all correct parameters and the code of the event handler is shown

Adding MouseClick event on System.Windows.Input.Mouse

(I am newbie and this is probably a duplicate question.)
To see which control is clicked on form, I have a method like this;
public void IdentifyControl(object sender, System.Windows.Input.MouseEventArgs e)
{
Control ctrl = sender as Control;
if (ctrl != null)
SelectedControl = ctrl;
this.Cursor = new System.Windows.Forms.Cursor(System.Windows.Forms.Cursor.Current.Handle);
MessageBox.Show(""+ctrl.GetChildAtPoint(System.Windows.Forms.Cursor.Position).ToString());
}
and trying to call it from mouse click.
In my first attempt, I added this function to main forms MouseClick event but it only worked for form itself but controls in form. Then I tried to create a general click event and use by Mouse class.
The main point I stuck is that I couldn't create the suitable parameters Mouse.AddMouseUpHandler(DependencyObject element,
MouseButtonEventHandler handler)
Its probably because of I don't know event handling but maybe I am all in a wrong way.
You can create a mouse click event just double clicking on any buttons, labels, etc, and the Visual studio will create a code for you, like this:
private void YOUROBJECT_Click(object sender, EventArgs e)
{
}
Just put the method you want into this click event.
Hope this can help you!

How to hide control when click outside it?

I have a WindowForm and some controls on it.
My point is that when I click button "?" on top-right of the datagridview, it will show a picture box and when I click outside the pictureBox, it must invisible.
My MainForm
MyPictureBox
I have searched some topics on this site, but some dont work, some work partly. Like
this.
I also tried:
void pictureBox1_LostFocus(object sender, EventArgs e)
{
if (pictureBox1.Visible)
pictureBox1.Visible = false;
}
But when I click on button2, button3, ... The pictureBox wasn't invisible.
Any solution will be highly appreciated.
I think your pictureBox1 isn't losing focus, cause it never actually GOT focused. Set it to be focused after making it visible.
Oh, I have encountered this before...
I was making a Label that you could double click and it would allow you to edit the Label.Text, like a TextBox. However, I was having problems hooking into the events to know when the user had clicked off the Control and wished to stop editing. I tried Control.LostFocus, and Control.Leave, but nothing. I even got frustrated/desperate and tried some silly ones like Control.Invalidated.
What I ended up having to do was subscribe to the Click event of the Form/Container/Control behind it.
However, putting the responsibility of wiring up this event into the Form that wants to use it is poor design. What you can do, however is to make the constructor to Control class require a reference to the owner/parent/container as a parameter. That way, the requirements are not hidden, they must be satisfied before you can get a object instance, and the control can wired up to the Form.Click within itself, where that logic belongs.
private Form owner;
public EditLabel(Form Owner)
{
this.owner = Owner;
owner.Click += EndEditing;
}
Add this method in designer.cs:
pictureBoxEvent this.MouseLeave += new EventHandler(pictureBox_MouseLeave);
Add this code in cs file:
private void pictureBox_MouseLeave(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}

Intercept every mouse click to WPF application

I'm looking to intercept every mouse click in my WPF application. Seems this should be easy with the command routing mechanism, but sorry I'm not finding anything.
My application implements several security levels, and has the requirement to automatically revert to the most restrictive level if no one interacts with (clicks) the application in x minutes. My plan is to add a timer that expires after x minutes and adjusts the security level. Each mouse click into the application will reset the timer.
You can register a class handler:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Window), Window.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
base.OnStartup(e);
}
static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Trace.WriteLine("Clicked!!");
}
}
This will handle any PreviewMouseDown event on any Window created in the application.
<Window .... PreviewMouseDown="Window_PreviewMouseDown_1">
</Window>
This should work for you.
This fires even if other MouseDown events fire for components that it contains.
As per Clemens suggestion in the comments, PreviewMouseDown is a better choice than MouseDown, as that makes sure you can't stop the event bubbling from happening in a different event.
You have a few options:
Low level mouse hook:
http://filipandersson.multiply.com/journal/item/7?&show_interstitial=1&u=%2Fjournal%2Fitem
WPF Solution (I'd check to see if this does what you need first):
WPF. Catch last window click anywhere

Triggering an event after a Winform layout is complete

I am working on a C# WinForm application.
I want to trigger some processing once the form has been "shown" and the layout of the form is complete.
I am using the "_Shown" event, but this seems to trigger before the layout of the form has completed. Is there event I can use that fires once the layout is complete?
Put Application.DoEvents() at the start of the form's Shown event handler. This will force all the controls to be rendered.
I don't see an event after Shown you can use for this purpose. Could you not use a timer to delay your processing in the Shown event?
An old trick in VB6 used to be to use the Paint event:
bool firstShown = false;
void form_Paint(Object sender, EventArgs e) {
if ( !firstShown ) {
YourMethodThatNeedsToRunOnShown();
firstShown = true;
}
//the rest of your paint method (if any)
}
It is a little hacky, but it does work
This works for me and is much less "hacky" than other suggestions:
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if(someControl == null)
return; // be careful of OnLayout being called multiple times
// otherwise, do some stuff here, set control sizes, etc.
}
AS far as I can remember the event order is something like
Form.Load
Form.Layout
Form.VisibleChanged
Form.GotFocus
Form.Activated
Form.Shown
So if something is still happening after Form.Show it's because of the way you coded it.
Are you maybe creating the form dynamically?
The best solution is the Shown() event: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
Try using Form.GotFocus (inherited from control)..
something like this.
private void Form1_Load(object sender, EventArgs e)
{
this.GotFocus += new EventHandler(Form1_gotFocus);
this.Focus();
}
private void Form1_gotFocus(object sender, EventArgs e)
{
// You will need to Switch focus from form at the end of this function,
//to make sure it doesnt keep Firing.
}
According To msdn , the following happens:
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl..::.ActiveControl property to the current form, focus events occur in the following order:
Enter
GotFocus
Leave
Validating
Validated
LostFocus

Categories

Resources