473,796 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to handle form events in C#

Hello,

I am absolute beginner in C# so pardon me if the following question is
too easy.

I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.

The ides is this:
Have a class (call it "controller ")
Controller opens the form
When I click the button the controller is "notified" by the form that
the button was clicked
The controller displays the message "Button was clicked"

Now, how do I accomplish this?

Thank you, Richard

Aug 26 '07 #1
10 7070
<me******@hotma il.comwrote in message
news:11******** ************@m3 7g2000prh.googl egroups.com...
I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.

The ides is this:
Have a class (call it "controller ")
Controller opens the form
When I click the button the controller is "notified" by the form that
the button was clicked
The controller displays the message "Button was clicked"

Now, how do I accomplish this?
One way to accomplish this is to publish an event in your form. When the
controller opens the form, it subscribes to the event of the form. In the
click event of the button, the only action that you take is to fire the
event that you published in your form. In this way, it gets "relayed" to the
controller.
Aug 26 '07 #2
Alberto,
Thank you for your reply
As I have mentioned I am a beginner with C# so I
need some code exmples.
"publish an event", "subscribe to the event" etc
what is the code that you use in your form and what
is the code that you use in your controller class?
"Alberto Poblacion" <ea************ *************** ***@poblacion.o rgwrote
in message news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
<me******@hotma il.comwrote in message
news:11******** ************@m3 7g2000prh.googl egroups.com...
>I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.

The ides is this:
Have a class (call it "controller ")
Controller opens the form
When I click the button the controller is "notified" by the form that
the button was clicked
The controller displays the message "Button was clicked"

Now, how do I accomplish this?

One way to accomplish this is to publish an event in your form. When
the controller opens the form, it subscribes to the event of the form. In
the click event of the button, the only action that you take is to fire
the event that you published in your form. In this way, it gets "relayed"
to the controller.


Aug 26 '07 #3
public class From
{
public event EventHandler BtnClicked;

private void Clicked(object o , eventrags e)
{
if(BtnClicked != null)
BtnClicked (o,e) ;
}
}

public class Controller
{

private void OpenFrom()
{
From frm = new From ();
frm.BtnClicked += new EventHandler(Fr omClickedHander );
Frm.shopw();
}

private void FromClickedHand er(object o , eventrags e)
{
.....
}

}
--
Sincerely
Yaron Karni
http://dotnetbible.blogspot.com/
"Richard_AU " wrote:
Alberto,
Thank you for your reply
As I have mentioned I am a beginner with C# so I
need some code exmples.
"publish an event", "subscribe to the event" etc
what is the code that you use in your form and what
is the code that you use in your controller class?
"Alberto Poblacion" <ea************ *************** ***@poblacion.o rgwrote
in message news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
<me******@hotma il.comwrote in message
news:11******** ************@m3 7g2000prh.googl egroups.com...
I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.

The ides is this:
Have a class (call it "controller ")
Controller opens the form
When I click the button the controller is "notified" by the form that
the button was clicked
The controller displays the message "Button was clicked"

Now, how do I accomplish this?
One way to accomplish this is to publish an event in your form. When
the controller opens the form, it subscribes to the event of the form. In
the click event of the button, the only action that you take is to fire
the event that you published in your form. In this way, it gets "relayed"
to the controller.


Aug 26 '07 #4
me******@hotmai l.com wrote:
Hello,

I am absolute beginner in C# so pardon me if the following question is
too easy.

I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.
That's fine. By default, when you double-click on a button, the VS
Designer creates a new method in the same form and adds some code to the
InitializeCompo nent() method that subscribes that method to the event.

But the delegate method that gets subscribed to the event can be any
delegate method from any class (as long as the method has the correct
signature, of course...that is, it has a "void" return type, and two
parameters, the first an "object" and the second an "EventArgs" ).

In general, you need a method that looks like this:

void ClickHandler(ob ject sender, EventArgs e) { ... }

And you need a reference to the button:

Button button = ...;

To subscribe, you just do this:

button.Click += ClickHandler;

Of course, the actual names can be anything you want. Also, since the
Click event is in the Control class, your variable need not actually be
of type Button; it can be Control if you like...you just have to make
sure you get the right control instance somehow.

If you set a Click handler the usual way in the Designer, and then go
look at the InitializeCompo nent() method, you'll see it does essentially
the same thing as the above.

On the assumption that your controller class is the one instantiating
form in the first place, it would be easy enough to subscribe to the
event at that time, from the controller class itself. The event is just
a member on the button, called "Click".

The one thing that's problematic is that, by default, control instance
variables in the form class are private. So the controller class would
not normally have direct access to the button's reference. However,
there are a number of ways around this:

* Make the button instance variable public. This is simply a
matter of setting the appropriate property in the Designer ("Modifiers"
under the "Design" category of properties). Then the controller can
access it through the form class, using the actual name of the variable.

* Enumerate the child controls. You can use Find() or similar on
the Form.Controls collection and look for the button control with the
name you want to watch. Once you have a reference to the instance, it's
a simple matter to subscribe to the event.

* Define some sort of API in the form class through which you can
pass a delegate instance to be subscribed to the button.

* Make the controller's handler method visible to the form class,
and let the form subscribe the handler to the event.

Finally, yes...you could do as Alberto suggests and define a whole new
event on the form class to which the controller can subscribe, and then
have the form mediate between that event and the button itself. But
IMHO, that's a waste. Your controller class can easily subscribe
directly to the button's event, and creating an event is -- while not
that difficult -- certainly an added complication that is in this case
wholly unnecessary.

Note that this is not a complete list. They are just some of the more
straightforward ways to deal with the issue. Which one is more
appropriate may well depend on other aspects of your design (for
example, you may not feel it's appropriate for the form class itself to
do things that seem like "controllin g the controller", such as the
fourth item above).

Hopefully this gets you pointed in the right direction.

Pete
Aug 26 '07 #5
"Richard_AU " <Ri*****@nospam .comwrote in message
news:v5******** **********@news-server.bigpond. net.au...
As I have mentioned I am a beginner with C# so I
need some code exmples.
"publish an event", "subscribe to the event" etc
what is the code that you use in your form and what
is the code that you use in your controller class?
To publish an event inside your form, you declare it inside your class
like this:

public event EventHandler TheButtonClicke d;

You then "fire" it from the click of the button:

protected void Button1_Click(o bject sender, EventArgs e)
{
if (TheButtonClick ed!=null) TheButtonClicke d(this, e);
}
The "controller " subscribes a routine to handle the event connecting the
routine to the event after creating the form:

TheForm f = new TheForm();
f.TheButtonClic ked += new EventHandler(My Routine);
f.Show();
....

private void MyRoutine(objec t sender, EventArgs e)
{
//Do something here
}

Aug 26 '07 #6
Thank you everyone for your assistance I now understand how to use this
events mechanism.

I got it to work but there is a little problem.
I can make it work if I create another form and from that form I load my
"controller " class.
How can I load my "controller " class when the application starts?
That is,when I start my application on the C# IDE it will load my controller
class, as a result my controller class opens my form.
Then if I click a button on that form it will instruct my controller class
to unload (resulting in closing my form)?

Thanks for you help
Richard

<me******@hotma il.comwrote in message
news:11******** ************@m3 7g2000prh.googl egroups.com...
Hello,

I am absolute beginner in C# so pardon me if the following question is
too easy.

I have a form with a one button. When I click the button I want to
display a message that reads "Button was clicked"
However, I do not want to handle the click event from that form,
instead I want to "transfer" that event to a "controller " class that
shows that message.

The ides is this:
Have a class (call it "controller ")
Controller opens the form
When I click the button the controller is "notified" by the form that
the button was clicked
The controller displays the message "Button was clicked"

Now, how do I accomplish this?

Thank you, Richard

Aug 26 '07 #7
Richard_AU wrote:
Thank you everyone for your assistance I now understand how to use this
events mechanism.

I got it to work but there is a little problem.
I can make it work if I create another form and from that form I load my
"controller " class.
How can I load my "controller " class when the application starts?
You mean, how do you get your controller class to actually be able to
act as the controller class, instead of the controlled class? :)

This is simple to do, once you understand the structure of the default
C# program when created within Visual Studio. The entry point for your
program is the Main() method found in the Program class, which is in the
Program.cs file. Check your Solution Explorer pane to find this easily.

In the Main() method, you'll want to change the code that by default
looks something like this:

Application.Run (new Form1());

Instead, you'll probably want to do something like instantiate the
controller class, let it instantiate your initial form, let the
controller class subscribe to whatever events are appropriate at the
time, and _then_ call Application.Run () with the form instance that the
controller created. You could even have the controller class itself
make the call to Application.Run (), which could give it a little more
control over application shutdown. Or you could have a method in the
controller class that returns the initial form.

Or, you could even have a static method in the controller that does all
of the instantiation of the controller and the initial form and then
returns that initial form.

If you did the latter, then the only change to the Program.Main() method
might look something like this:

Application.Run (Controller.For mStartup());

where the Controller.Form Startup() method creates the actual controller
instance, creates the initial Form instance, subscribes the controller
instance methods to the initial Form's event as necessary, and then
returns the reference to the Form instance.

Now, all that said...

For yet another perspective on how this might work: I don't think it'd
be the end of the world if you just wanted the initial form's
constructor to instantiate the controller. Yes, it would mean that the
controller itself isn't really doing the instantiation of the initial
form, which seems a little backwards. It also means that the form class
winds up perhaps knowing more about the controller than would normally
be the case. But as long as the controller semantics are otherwise
adhered to, I don't think that devalues the use of a controller class.

In fact, if you make the controller a singleton class with the usual
static Instance property, you can either instantiate the controller
lazily (on the first call to the Instance property getter), or in a
static constructor for the class. Either way would allow you to not
only leave the default Program.Main() method as-is, but would also avoid
having the controller's instantiation explicitly tied to code within
your initial form; _any_ form that ever accesses the controller class
could be used and the controller class would get created implicitly in
the process.

So, for example, you might design it so that rather than the controller
class creating that initial form, the form "registers" itself with the
controller in its constructor, allowing the controller to at that time
do whatever event subscription, etc. it needs to do. You could in fact
make that the design for all forms; controlled instances always need to
register themselves, which is the point at which the controller then
hooks up whatever event handling, etc. it wants.

IMHO, "design patterns" such as singleton, controller, etc. are for your
benefit. Adhering closely to them is often the best way to get the most
value out of them, but if there seems to be a benefit in deviating a
little from the pattern, and you can do so knowing exactly what
implications that has with respect to the overall design, I don't think
it's terrible to do so. Better to deviate a little, than to corrupt
some other part of the design just to get the design pattern to be exact
(not that I think that changing Program.Main() is a corruption...in this
case it's just a matter of what seems easier or cleaner to you).

Pete
Aug 26 '07 #8
Peter,

Thank you for this exmplanation
Any chance of a small code example?
Richard

"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:13******** *****@corp.supe rnews.com...
Richard_AU wrote:
>Thank you everyone for your assistance I now understand how to use this
events mechanism.

I got it to work but there is a little problem.
I can make it work if I create another form and from that form I load my
"controller " class.
How can I load my "controller " class when the application starts?

You mean, how do you get your controller class to actually be able to act
as the controller class, instead of the controlled class? :)

This is simple to do, once you understand the structure of the default C#
program when created within Visual Studio. The entry point for your
program is the Main() method found in the Program class, which is in the
Program.cs file. Check your Solution Explorer pane to find this easily.

In the Main() method, you'll want to change the code that by default looks
something like this:

Application.Run (new Form1());

Instead, you'll probably want to do something like instantiate the
controller class, let it instantiate your initial form, let the controller
class subscribe to whatever events are appropriate at the time, and _then_
call Application.Run () with the form instance that the controller created.
You could even have the controller class itself make the call to
Application.Run (), which could give it a little more control over
application shutdown. Or you could have a method in the controller class
that returns the initial form.

Or, you could even have a static method in the controller that does all of
the instantiation of the controller and the initial form and then returns
that initial form.

If you did the latter, then the only change to the Program.Main() method
might look something like this:

Application.Run (Controller.For mStartup());

where the Controller.Form Startup() method creates the actual controller
instance, creates the initial Form instance, subscribes the controller
instance methods to the initial Form's event as necessary, and then
returns the reference to the Form instance.

Now, all that said...

For yet another perspective on how this might work: I don't think it'd be
the end of the world if you just wanted the initial form's constructor to
instantiate the controller. Yes, it would mean that the controller itself
isn't really doing the instantiation of the initial form, which seems a
little backwards. It also means that the form class winds up perhaps
knowing more about the controller than would normally be the case. But as
long as the controller semantics are otherwise adhered to, I don't think
that devalues the use of a controller class.

In fact, if you make the controller a singleton class with the usual
static Instance property, you can either instantiate the controller lazily
(on the first call to the Instance property getter), or in a static
constructor for the class. Either way would allow you to not only leave
the default Program.Main() method as-is, but would also avoid having the
controller's instantiation explicitly tied to code within your initial
form; _any_ form that ever accesses the controller class could be used and
the controller class would get created implicitly in the process.

So, for example, you might design it so that rather than the controller
class creating that initial form, the form "registers" itself with the
controller in its constructor, allowing the controller to at that time do
whatever event subscription, etc. it needs to do. You could in fact make
that the design for all forms; controlled instances always need to
register themselves, which is the point at which the controller then hooks
up whatever event handling, etc. it wants.

IMHO, "design patterns" such as singleton, controller, etc. are for your
benefit. Adhering closely to them is often the best way to get the most
value out of them, but if there seems to be a benefit in deviating a
little from the pattern, and you can do so knowing exactly what
implications that has with respect to the overall design, I don't think
it's terrible to do so. Better to deviate a little, than to corrupt some
other part of the design just to get the design pattern to be exact (not
that I think that changing Program.Main() is a corruption...in this case
it's just a matter of what seems easier or cleaner to you).

Pete

Aug 26 '07 #9
Richard_AU wrote:
Thank you for this exmplanation
Any chance of a small code example?
Of what? One downside of my rambling is that I offered a number of
design possibilities. You haven't narrowed the question down much from
my broad offering. :)

That said, I would probably go with the "static method in controller
class returning the form" design, if it were me. That might look
something like this:

class Program
{
static void Main()
{
// ... VS-supplied initialization
Application.Run (Controller.For mStartup());
}
}

class Form1 : Form
{
// this would be your usual Form-derived class.

// I've assumed that you've simply made the button
// instance public for the purpose of subscribing
// to its events.
}

class Controller
{
public static Form FormStartup()
{
Controller controller;
Form1 form1;

controller = new Controller();
form1 = new Form1();
form1.button1.C lick += controller.Clic kHandler;
return form1;
}

private void ClickHandler(ob ject sender, EventArgs e)
{
// do whatever in response to click event here
}
}

Hope that helps,
Pete
Aug 27 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2069
by: lkr | last post by:
hi is there is anyway to capture the document events of a MSWord?eg:I have to handle the event awhen WM_KEYUP or anyother events will occur. give me a solution............ thanks in advance lkr
3
3122
by: Sharon | last post by:
I’m using a DataGrid control on my form; and I want to handle the KeyUp event. So I did: myDataGrid.KeyUp += new KeyEventHandler(this.OnKeyUp); When the DataGrid is empty, I mean when It has no data so now rows are seen, all keys are causing my this.OnKeyUp(...) to be invoked correctly. But when the DataGrid is populated with some data (rows are seen with only DataGridTextBoxes), only several keys are causing it to be invoked.
0
1221
by: Rajiv Das | last post by:
Environment: Visual Studio 2005, Beta 2 ..Net 2.0 Windows XP, SP2 C# Generics ------------------------------- Hi, I have a Windows Form whose contents I would like to dynamically change. I
15
4058
by: Adam J. Schaff | last post by:
I have noticed that if a user closes a form via pressing return (either while the OK button has focus or if AcceptButton is set to OK for the form) then the "ENTER" keypress event fires ON THE CALLING FORM! This is very bad for me, because in my application, Form1 responds to an ENTER keypress by calling Form2. If the user closes Form2 via an ENTER, then Form1 just reopens it again, kind of trapping the user in Form2 (they can still close...
3
1805
by: Jerry Wei | last post by:
Dear all: I have a problem about how to handle the events. For example, there are two forms, Form1 and Form2. Form2 is owned by Form1 and there is a button,Button1, in Form2. It is no problem for Form2 to handle the event "Button1.Click" . My problem is how to handle the Button1.click event in Form1 as Form2's owner. Is there any way to achieve this demand??? ================================================================= owner and...
3
1848
by: elziko | last post by:
I have a procedure that creates a bitmap of a certain size and then displays it in a 3rd party component. However, if the bitmap is very large then a System.OutOfMemoryException is thrown my something but my codes breaks at the difition of my class: "Public Class MainForm" ....so I'm assuming that the OutOfMemoryException occurs in the 3rd party since I have put a Try-Catch block around my bitmap creation code and I am
4
6888
by: yhlove | last post by:
Hi I would like to know how can I handle the event that the user press the red button "X" (The button which suppose to close the program) ? I tried to double click on it (in the form editor) but nothing happened... Thanks Yhlove
2
2847
by: Boki | last post by:
Hi All, We can process the mouse/keyboard events by handling, however, how to create a event on a target form ( ex: webbrowser ) ? Thanks! Best regards, Boki.
0
1439
by: Marc Bartsch | last post by:
Hi, I have a WinForms application (C#, VS 2005) that consists of a treeview control and a notify icon. Below is a complete example of this application. The treeview has one root node and one child node. When I close the form, it will not be closed but minimised to the system tray. A double-click on the notify icon wakes it up and displays it again. My expection was that the treeview handle would be destroyed when the form is sent to the...
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10017
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.