C# WinForm multiple click event handlers for similar function - c#

I have a few toolStripMenuItems that act as a useful links for a series of websites, a rough example of the code would be something like:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Process.Start("http://www.google.com");
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
Process.Start("http://www.bing.com");
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
Process.Start("https://www.duckduckgo.com");
}
private void toolStripMenuItem4_Click(object sender, EventArgs e)
{
Process.Start("http://www.yahoo.com/");
}
...
Is there a more elegant way to handle this?

Put urls in menu items tag and attach this handler to all of them (hope it works)
private void toolStripMenuItemClick(object sender, EventArgs e)
{
Process.Start(sender.Tag.ToString());
}

The first thing to do is use the same handler for each one:
toolStripMenu1.Click += toolStripItemClick;
toolStripMenu2.Click += toolStripItemClick;
// etc
I would use the Tag property for this, set it when you're constructing the toolStripItems:
toolStripMenu1.Tag = "http://www.google.com";
And then define your handler:
private void toolStripItemClick(object sender, EventArgs e)
{
var c = (ToolStripMenuItem)sender;
Process.Start(c.Tag.ToString());
}

"Mash" all of the event handlers into one and then use the sender to see what ToolStripMenuItem was clicked.
private void toolStripMenuItem_Click(object sender, EventArgs e)
{
if(sender == toolStripMenuItem1)
Process.Start("http://www.google.com");
else if(sender == toolStripMenuItem2)
Process.Start("http://www.bing.com");
else if(sender == toolStripMenuItem3)
Process.Start("http://www.duckduckgo.com");
else if(sender == toolStripMenuItem4)
Process.Start("http://www.yahoo.com");
}
Or as Artem notes use the Tag member of the Control to store the String representing which site to visit. Then cast the sender.Tag to a String and use it.
toolStripMenuItem1.Tag = "http://www.google.com";
toolStripMenuItem2.Tag = "http://www.bing.com";
toolStripMenuItem3.Tag = "http://www.duckduckgo.com";
toolStripMenuItem4.Tag = "http://www.yahoo.com";
...
private void toolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start(sender.Tag.ToString());
}

You can also subscribe to click event using a lambda expression:
toolStripMenuItem1.Click += (_, __) => Process.Start("process1");
toolStripMenuItem2.Click += (_, __) => Process.Start("process2");

Related

Show button only when focus is on textbox

Is this possible to display button on Windows Form only when focus is on specific textbox?
Tried that with this approach:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
button3.Visible = false;
}
No luck, because button click does not work then, because button is hidden immediately after textbox lost focus, preventing it from firing button3_Click(/*...*/) { /*...*/ } event.
Now I'm doing it like that:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
//button3.Visible = false;
DoAfter(() => button3.Visible = false);
}
private async void DoAfter(Action action, int seconds = 1)
{
await Task.Delay(seconds*1000);
action();
}
Form now waits for a second and only then hides button3.
Is there any better approach?
I think you want to display the button only when focus is on specific textbox or the focus is on the button.
To do this you can check the Focused property of button3 in the Leave event of textBox2 and only hide the button if the button doesn't have focus. Note that the button will get focus before the Leave event of textBox2 fires.
You will then need to hide the button in the scenario where button3 loses focus and the focus moves to somewhere other than textBox2. You can use exactly the same technique here by handling the Leave event of button3 and only hiding button3 if textBox2 does not have focus.
The following code should fit your requirements:
private void textBox2_Leave(object sender, EventArgs e)
{
if (!button3.Focused)
{
button3.Visible = false;
}
}
private void button3_Leave(object sender, EventArgs e)
{
if (!textBox2.Focused)
{
button3.Visible = false;
}
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked");
}
Why not work with the GotFocus and LostFocus event of the TextBox?
private void textBox2_GotFocus(object sender, EventArgs e)
{
button3.Visible = true;
}
Then hide the button on the click event.
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
button3.Visible = false;
}
How about you add a Panel and place the button and text boxes in that panel and when user MouseHovers that Panel then display the button...
This way user would be able to click on the button...
This is the event you are looking for, I think...
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousehover(v=vs.110).aspx
UPDATE:
var textboxFocussed = false;
private void textBox2_Enter(object sender, EventArgs e)
{
textboxFocussed = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
textboxFocussed = false;
}
UPDATE 2
private void Panel_GotFocus(object sender, EventArgs e)
{
button3.Visible = textboxFocussed;
}
private void Panel_LostFocus(object sender, EventArgs e)
{
button3.Visible = false;
}
Here are the details of the Panel Events
you can add Enter event handler for all controls on form at Load. Just make sure to skip the controls on which you want to show the button.
List<string> strControlException = new List<string>();
public Form1()
{
InitializeComponent();
strControlException.Add("btnMain");
strControlException.Add("txtMain");
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < this.Controls.Count;i++ )
{
if (!strControlException.Contains(Controls[i].Name))
{
Controls[i].Enter += new EventHandler(hideButton);
}
}
}
private void txtMain_Enter(object sender, EventArgs e)
{
btnMain.Visible = true;
}
private void hideButton(object sender, EventArgs e)
{
btnMain.Visible = false;
}
btnMain (Button you want to Manipulate) and txtMain (Which controls the vibility of the button) are the controls in contention here
Add more controls on the form to test.
Explanation for the above code :
First initialize a list with the names of controls that should show the Button
On Form Load add an Event handler to all controls (except the one in our list)
In the handler function hide the button. (You might want to perform more logic here based on the control that called this function)
Button is hidden by default and only on textbox Enter event we show the button.

On c# the mousehover on a picturebox appear to do nothing.Do i need some kind of eventhandler?

I am trying to create a MouseHover event for a pictureBox, but I have had no luck so far:
private void pictureBox1_MouseHover(object sender, EventArgs e)
{
pictureBox1.Image = ArgyroCinema.Properties.Resources.ktz00h07;
label1.Text = "hover";
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = ArgyroCinema.Properties.Resources.ktz00h07;
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
pictureBox1.Image = ArgyroCinema.Properties.Resources.ktz00h07;
}
What is going on here? MouseClick works correctly, maybe I have to add something on Form1.Designer.cs ?
ok i had to add this line on the constructor:
this.pictureBox1.MouseHover += new System.EventHandler(this.pictureBox1_MouseHover);
although i will use mouseenter, its faster

C# WindowsForms - Radio button comment/uncomment content of textbox keypress, textchanged and focusleave

i have 3 radio buttons:
rbtPercentualmedioanual
rbtPercentualmensal
rbtValorfixo
I would like to change options events for textbox1 according choosed option
If chose rbtValorfixo,
It will uncomment:
private void textbox1_TextChanged(object sender, EventArgs e)
{
//substituipontovirgula_textBox(sender as TextBox, e);
}
private void textbox1_Leave(object sender, EventArgs e)
{
//formatamoeda_textBox(sender as TextBox, e);
}
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
//numeropontoouvirgula_textBox(sender as TextBox, e);
formatarporcentagem_textBox(sender as TextBox, e);
}
and will comment
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
numeropontoouvirgula_textBox(sender as TextBox, e);
//formatarporcentagem_textBox(sender as TextBox, e);
}
If choose option rbtPercentualmedioanual or rbtPercentualmensal, it will comment:
private void textbox1_TextChanged(object sender, EventArgs e)
{
substituipontovirgula_textBox(sender as TextBox, e);
}
private void textbox1_Leave(object sender, EventArgs e)
{
formatamoeda_textBox(sender as TextBox, e);
}
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
numeropontoouvirgula_textBox(sender as TextBox, e);
//formatarporcentagem_textBox(sender as TextBox, e);
}
and will uncomment: formatarporcentagem_textBox
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
//numeropontoouvirgula_textBox(sender as TextBox, e);
//formatarporcentagem_textBox(sender as TextBox, e);
}
i dont know how comment/uncomment keypress, textchanged or focusleave event using radiobutton check, only say how, not need make all, i can do it, but i have to know if its possible and if is, how ?
Thanks
You can determine if a radiobutton or checkbox is checked by the radioButton.Checked property.
In you case it will be something like this:
private void textbox1_TextChanged(object sender, EventArgs e)
{
if(!rbtValorfixo.Checked)
substituipontovirgula_textBox(sender as TextBox, e);
}
or:
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(rbtValorfixo.Checked)
numeropontoouvirgula_textBox(sender as TextBox, e);
else
formatarporcentagem_textBox(sender as TextBox, e);
}
and so on.
You don't need to comment or uncommment code. Being within a programming language, you need to look out for right structures.
In this rather simple case, you just need an "if" block.
This might help
You may want to use something like this? Not sure as it's quite unclear what you are trying to say.
private void Operation_Changed(object sender, EventArgs e)
{
RadioButton rbt = sender as RadioButton;
if (btn != null)
{
case "rbtPercentualmedioanual":
_operation = new example2();
example1.Visible = true;
example2.Visible = true;
example3.Visible = false;
return;
case "rbtPercentualmensal":
_operation = new example3();
example1.Visible = true;
example2.Visible = true;
example3.Visible = false;
return;
case "rbtValorfixo":
_operation = new example1();
example1.Visible = true;
example2.Visible = true;
example3.Visible = false;
default:
break;
And change it to what you want to show

C# DragDrop from toolStrip

I'm looking for a way to determine which item in a toolStrip that was dragged after a DragDrop event has occured, all I want to do is make a switch case with different cases for each item in the toolstrip but I cant seem to find a way of comparing them.
UPDATE: SHORT CODESAMPLE
private void toolStrip1_DragDrop(object sender, DragEventArgs e)
{
//Here I want something like a DoDragDrop() and send the specific item from the
//toolstrip..
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
//And here some way to determine which of the items was dragged
//(I'm not completely sure if I need a mouseUp event though..)
}
Hopefully a bit easier to get what I'm trying to do.
The events in your example don't look like the correct events to use.
Here is a working example from a ToolStrip that has 2 ToolStripButtons on it:
public Form1() {
InitializeComponent();
toolStripButton1.MouseDown += toolStripButton_MouseDown;
toolStripButton2.MouseDown += toolStripButton_MouseDown;
panel1.DragEnter += panel1_DragEnter;
panel1.DragDrop += panel1_DragDrop;
}
void toolStripButton_MouseDown(object sender, MouseEventArgs e) {
this.DoDragDrop(sender, DragDropEffects.Copy);
}
void panel1_DragEnter(object sender, DragEventArgs e) {
e.Effect = DragDropEffects.Copy;
}
void panel1_DragDrop(object sender, DragEventArgs e) {
ToolStripButton button = e.Data.GetData(typeof(ToolStripButton))
as ToolStripButton;
if (button != null) {
if (button.Equals(toolStripButton1)) {
MessageBox.Show("Dragged and dropped Button 1");
} else if (button.Equals(toolStripButton2)) {
MessageBox.Show("Dragged and dropped Button 2");
}
}
}

Adding delegate functions first single use

I have a button which slides out a menu using a storyboard by calling begin() on it like so
private void ShareBtn_Click(object sender, RoutedEventArgs e)
{
SlideIn.Begin();
}
On the grid which then slides out there are buttons.
Each button then slides the grid back and when that storyboard completes the action for the button then runs so like so,
private void PictureBtn_Click(object sender, RoutedEventArgs e)
{
CertificateDisplay.SaveAsPicture();
}
private void FacebookBtn_Click(object sender, RoutedEventArgs e)
{
App.facebookSuccess = false;
NavigationService.Navigate(new Uri("/FBLogin.xaml", UriKind.Relative));
}
private void SMSBtn_Click(object sender, RoutedEventArgs e)
{
SlideOut.Begin();
SlideOut.Completed += delegate(object s, EventArgs se) { SlideOut_Completed(s, se, "Email"); };
}
private void EmailBtn_Click(object sender, RoutedEventArgs e)
{
SlideOut.Begin();
SlideOut.Completed += delegate(object s, EventArgs se) { SlideOut_Completed(s, se, "Email"); };
}
void SlideOut_Completed(object sender, EventArgs e, String shareType)
{
switch (shareType)
{
case "Email":
...
default:
break;
}
}
The flaw I encountered if that I cannot remove the anonymous functions from the event stack.
I've managed to solve it by making shareType a common variable for all of the above functions and not using a anonymous delegate and then removing the "named" functions from the event stack when OnNavigatedFrom is called.
Is there a way to do this by still using those delegates because it looks neater?
One option is to remove it within the handler itself:
EventHandler handler = null;
handler = delegate(object s, EventArgs se) {
SlideOut_Completed(s, se, "Email");
SlideOut.Completed -= handler;
};
SlideOut.Completed += handler;
SlideOut.Begin();
Why assign the Completed event handler EmailBtn_Click at each click? Do it in the form constructor or in the form load event.

Categories