Storing Info Between Events
-
Hi Luc, thanks for replying. I have searched for a way to "put the state inside the button itself" like you have suggested but all I've found were maintaining session state for web apps and not windows form apps. I'm also interested in your suggestion to "hide the state in the Tag property" but I can't find an example of how to do that either. Please give me links to articles on how to do those things I've just mention if you can. Thanks again for your help.
Sorry for the delay. If you want to keep number of clicks inside the button, all you have to do is subclass Button class and add a field with the number of clicks. Then, override the OnClick method to increase the number of clicks by one every time the button is clicked. Don't forget to call the parent OnClick so that the normal button click behavior is executed. You have an example below.
using System;
using System.Drawing;
using System.Windows.Forms;class CountClickButton : Button {
int clickCount; // Number of clicks public CountClickButton() { clickCount = 0; } // OnClick is called when the button is clicked. It must increase clickCount by one // and then execute the event handlers (which is done when base.OnClick // is executed). protected override void OnClick(EventArgs e) { clickCount = clickCount + 1; base.OnClick(e); } // Only allow other classes to read number of clicks. Number of clicks cannot be // modified by other classes. public int ClickCount { get { return clickCount; } }
}
class CountClickForm : Form {
CountClickButton b; public CountClickForm() { b = new CountClickButton(); b.Text = "Click me!"; b.Size = b.PreferredSize; ClientSize = new Size(700, 400); // Should be big enough. Fit to your own needs. b.Left = (ClientSize.Width - b.Width) / 2; b.Top = (ClientSize.Height - b.Height) / 2; b.Click += new EventHandler(b\_clicked); Controls.Add(b); Text = "I count clicks!"; } // b\_clicked is registered as an event. It will be executed when button is clicked, // after number of clicks is increased by one. void b\_clicked(object sender, EventArgs e) { string text = String.Format("Button has been clicked {0} times.", b.ClickCount); if (b.ClickCount < 1) { // This should never happen. text = "Sorry, I was drunk when programming this. Cheers!!"; } if (b.ClickCount == 1) { text = "Button has been clicked once."; } if (b.ClickCount == 2) { text = "Button has been clicked twice."; } Text = text; } \[STAThreadAttribute\] static void Main() { Application.Run(new CountClickForm()); }
}