Everyone, I am just so new to C#, please help me...
I would like to add WndProc to process messages, I have look into properties but I don't see the thunderbolt to display function name so I can add one I like. I search the internet and see WndProc as
protected override void WndProc(ref Message msg)
{
//do something
}
I would like it to be generated for me, not to type it down ?
WndProc is not a .NET event handler; it's a window procedure, part of the native Win32 API. You won't get any code generation for it as an event handler in Visual Studio.
In Windows Forms all you have to do is override a form's existing WndProc() method and start coding. As it's found in the Form class, there is an autocomplete option for it if you type the following:
override WndProc
which then generates:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
just to make this perfectly clear: it's rather improbable that you ever have to do something with WndProc inside winforms/wpf/whatever in the .net world.
All this nasty stuff is abstracted and hidden away from you and I don't know a single case where I really needed/missed it.
In Winforms you just wire up events with
Eventname += EventHandlerMethod;
(or you can do such more advanced stuff with annonymous methods and lambdas but don't concern yourself to much with it at the moment).
The easiest way is to just use the Designer and hook your events there:
After subscribed to a event with this tool the editor will show you the handler it created and you can start coding away.
Here is a quick example:
I just started a new project and added a single button "button1" onto the form:
then I hook up the OnClick-Event of the button (select the button and goto the event-tab):
and finaly I added code to change the buttons text to "clicked" into the codebehind:
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace StackOverflowHelp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// the following line is from InitializeComponent - here you can see how the eventhandler is hook
// this.button1.Click += new System.EventHandler(this.OnButton1Clicked);
}
private void OnButton1Clicked(object sender, EventArgs e)
{
var button = sender as Button; // <- same as button1
if (button == null) return; // <- should never happen, but who is to know?
button.Text = "clicked";
}
}
}
that's all. The nasty dispatching of events is done by the framework.
Related
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
I am watching tutorial where Form1_Load() is included
I am watching tutorial where Form1_Load() is included, is there another way to include TextBox items by coding?
CSharp and VB.NET are a bit different on how to write event handlers. In your case, you need to tell the forms designer you want to handle the .Load event.
Find the properties window in the designer for the form, and click on the lightning bolt.
Now the properties window displays all the events that the form can trigger. Find Load and double-click on the space next to it.
The designer will now generate the Form1.Load() method you are missing
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
An alternative way to do this same thing.
In the form constructor type this.Load += and then press the [Tab] button.
Visual studio will fill in the code needed to handle the event wit the option to rename the event handler
A third way of handling the Load event
My preferred way is to override the OnLoad() method in the form.
Type override OnLoad inside the class, and IntelliSense is going to prompt you the method to override. Select OnLoad and press [Tab].
Now you can write the same code you would have before, but inside the OnLoad() method which gets called automatically every time the .Load event triggers.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Write code here
}
}
Yes in the 20+ years of WinForms programming and VisualStudio development some redundancies have developed. It is not a bad thing, as VS needs to accommodate different coding styles.
There is a 4th way, that applies to VB.NET and involves the Handles keyword which makes more logical sense IMHO than the way C# does things, but that is just me.
You can "wire up" events via code.
Here's an example with the Load() event of the Form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
This can be done with any control and event, but it's easier to do via the IDE as described by Jeroen van Langen. If you're creating dynamic controls (created at run-time) then this is the way to do it.
Go to your form designer and make sure the form control self is selected. press F4 for the properties control. Press on the lightning icon for events and search for the Load event.
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
I have a User Control for typical CRUD like actions on my WinForm app.
Validate, Insert, Update, Clear, Cancel, and Delete.
On every form I put this on I end up adding the click event, ucPersonNav.btnValidate.Click += new EventHandler(btnValidate_Click);, for every button.
What I am wondering is can I have the Events be on the User Control themselves and just have them point to a Method that I override on a Form by Form basis?
Something like this -->
namespace psUserControls
{
using System;
using DevExpress.XtraEditors;
public partial class ucVIUCCDwithWhoDoneIt : XtraUserControl
{
public ucVIUCCDwithWhoDoneIt()
{
InitializeComponent();
}
private void btnValidate_Click(object sender, EventArgs e)
{
ValidateEvent();
}
}
}
And then on a Form have this -->
void ValidateEvent()
{
if (dxValidDiagnosis.Validate())
{
if (planDiagnosisID != 0)
{
ucNavDiagnosis.btnUpdate.Enabled = true;
ucNavDiagnosis.btnDelete.Enabled = true;
}
ucNavDiagnosis.btnInsert.Enabled = true;
}
}
Is this feasible? Is it idiotic? If Yes then No then what steps do I need to take to make this work?
Thanks
i think .. not a bad idea..
but the approach would be very specific to your application.
we can have an enum for CRUD buttons - 6 enum items as you specified.
We can have a single event handler - delegate which takes above enum as a parameter.
Write an event (MyButtonClickedEvent) for this delegate which will be fired on each button clicked event.
on your control, on each button clicked event you can fire this event with respective enum item as a parameter.
e.g. on Validate button click, fire MyButtonClickedEvent with parameter as validate enum item.
On Inser button click, fire same MyButtonClickedEvent with parameter as Insert enum item.
This way you will have to handle single event on your form. You will be firing different events from your control. But this is to be done only once. On your form you will write a just one single handler - Method. In this method, you can differentiate depending on the enum type. .Net supports enum in switch-case construct. So you can easily identify the opteration that you have to perform.
All the users of your control will find it easier as they have to handle just one event. They will ignore the cases in switch construct which they are not interested.
Hope this helps.
You just need to define ValidateEvent as an event. In your UserControl:
public event EventHandler ValidateEvent;
On the form:
ucNavDiagnosis.ValidateEvent += new EventHandler(<name of event handler function>);
It's probably not a great idea to be accessing the buttons of the UserControl directly, however.
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.
Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?
I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.
Any suggestions?
What kind of crazy mobile device do
you have that has a mouse? :)
Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.
Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.
According to the .Net Framework, the
MouseDown Event Handler on a TextBox
is supported. What happens when you
try to run the code?
Actually, that's only there because it inherits it from "Control", as does every other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.
However, you actually can write the code:
textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.
I know this answer is way late, but hopefully it ends up being useful for someone who finds this. Also, I didn't entirely come up with it myself. I believe I originally found most of the info on the OpenNETCF boards, but what is typed below is extracted from one of my applications.
You can get a mousedown event by implementing the OpenNETCF.Windows.Forms.IMessageFilter interface and attaching it to your application's message filter.
static class Program {
public static MouseUpDownFilter mudFilter = new MouseUpDownfilter();
public static void Main() {
Application2.AddMessageFilter(mudFilter);
Application2.Run(new MainForm());
}
}
This is how you could implement the MouseUpDownFilter:
public class MouseUpDownFilter : IMessageFilter {
List ControlList = new List();
public void WatchControl(Control buttonToWatch) {
ControlList.Add(buttonToWatch);
}
public event MouseEventHandler MouseUp;
public event MouseEventHandler MouseDown;
public bool PreFilterMessage(ref Microsoft.WindowsCE.Forms.Message m) {
const int WM_LBUTTONDOWN = 0x0201;
const int WM_LBUTTONUP = 0x0202;
// If the message code isn't one of the ones we're interested in
// then we can stop here
if (m.Msg != WM_LBUTTONDOWN && m.Msg != WM_LBUTTONDOWN) {
return false;
}
// see if the control is a watched button
foreach (Control c in ControlList) {
if (m.HWnd == c.Handle) {
int i = (int)m.LParam;
int x = i & 0xFFFF;
int y = (i >> 16) & 0xFFFF;
MouseEventArgs args = new MouseEventArgs(MouseButtons.Left, 1, x, y, 0);
if (m.Msg == WM_LBUTTONDOWN)
MouseDown(c, args);
else
MouseUp(c, args);
// returning true means we've processed this message
return true;
}
}
return false;
}
}
Now this MouseUpDownFilter will fire an MouseUp/MouseDown event when they occur on a watched control, for example your textbox. To use this filter you add some watched controls and assign to the events it might fire in your form's load event:
private void MainForm_Load(object sender, EventArgs e) {
Program.mudFilter.WatchControl(this.textBox1);
Program.mudFilter.MouseDown += new MouseEventHandler(mudFilter_MouseDown);
Program.mudFilter.MouseUp += new MouseEventHandler(mudFilter_MouseUp);
}
void mudFilter_MouseDown(object sender, MouseEventArgs e) {
if (sender == textBox1) {
// do what you want to do in the textBox1 mouse down event :)
}
}
Looks like you're right. Bummer. No MouseOver event.
One of the fallbacks that always works with .NET, though, is P/Invoke. Someone already took the time to do this for the .NET CF TextBox. I found this on CodeProject:
http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx
Hope this helps
Fair enough. You probably know more than I do about Windows Mobile. :) I just started programming for it. But in regular WinForms, you can override the OnXxx event handler methods all you want. A quick look in Reflector with the CF shows that Control, TextBoxBase and TextBox don't prevent you from overriding the OnMouseDown event handler.
Have you tried this?:
public class MyTextBox : TextBox
{
public MyTextBox()
{
}
protected override void OnMouseDown(MouseEventArgs e)
{
//do something specific here
base.OnMouseDown(e);
}
}
is there an 'OnEnter' event that you could capture instead?
it'd presumably also capture when you tab into the textbox as well as enter the text box by tapping/clicking on it, but if that isn't a problem, then this may be a more straightforward work-around
According to the .Net Framework, the MouseDown Event Handler on a TextBox is supported. What happens when you try to run the code?