Reject Enter from activating the click action - c#

I would like to help with my new clicker game that I'm working on and I've stumbled upon a problem with adding a value to the "playerPoints" which is from launch 0. You need to click a button which is called "button_click" which will add +1 (++) to your "playerPoints". But there is a bug when you click the button and then hold the enter button it will act like a little auto clicker which I don't want. Is there a way how to prevent the enter key to add value when it is pressed or held down? Thanks in exchange.
int playerPoints = 0;
public void button_click_Click(object sender, EventArgs e) // main click button
{
playerPoints++;
label_points.Text = playerPoints.ToString() + " BITS";
}

The problem has been solved by an great idea by: Dan Byström
If you don't want to make the button respond to keys like enter.
Use a simple image or label and link that function to the image_click or label_click
again thanks alot guys!

When you click on the subject Button, it becomes the form's ActiveControl. As part of the form's internal processing in setting the ActiveControl, the Form.UpdateDefaultButton Method is called.
Remarks
The UpdateDefaultButton method determines which button on the form raises its Click event when the user presses ENTER, according to the following priority:
To avoid having the subject button becoming the Default Button, override the form's UpdateDefaultButton method with something like this:
protected override void UpdateDefaultButton()
{
if (ActiveControl == button_click)
{
return;
}
else
{
base.UpdateDefaultButton();
}
}

Hook the KeyDown event instead of the Click event.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keydown
Button.KeyDown += Button_KeyDown;
// Handle the KeyDown event
private void Button_KeyDown(object sender, KeyEventArgs e)
{
//increment your counter
}

Related

C# If Button IsEnabled, its triggering event on click

I have next issue, I am working on small c#-wpf application,
and on load I am disabling button which is ussualy used to do some action on click, and it looks like this:
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
if (String.IsNullOrEmpty(password.Password))
{
btnActivate.IsEnabled=false;
}
}
and somewhere I am checking my password field, for example:
private void password_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.Enter))
{
if (password.Password == "drag0n")
{
btnActivate.IsEnabled = true;
}
else
{
btnActivate.IsEnabled = false;
}
}
}
And my problem is next, when user enter "drag0n" and press enter, button should be just enabled, but its not only enabled, its calling automatic his event _Click, I don't know why does that happening, because in that case, if my button is just enabled event _Click is also called, and if user clicks on that button, event is called again, so actually my event onclick is called twice.
My question is how can I stop calling my Click event if I set IsEnabled=true. When I set IsEnabled=true I just want it to be enabled for pressing and I don't want execute event _Click.
I want to execute event _Click only when my button is pressed as it should work and not on IsEnabled=true.
Thanks guys,
Cheers
On click event occurs when you press Enter key, because this button is the default control in a form.
If you don't want click event on Enter key, you should either make this button not default or not process Enter key pressing in your button click (e.Handled = true -> when Enter is pressed).
Or try to change your code:
private void password_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.Enter))
{
if (password.Password == "drag0n")
{
e.Handled = true; // add this line
btnActivate.IsEnabled = true;
}
else
{
btnActivate.IsEnabled = false;
}
}
}

C# checkbox and mouse click event

I am self teaching myself C# and ran into a problem I haven't seem to find an answer too. I have a Form that when I mouse click the check box the state goes to true but also immediately triggers the mouse click event I have code follows:
private void uxCheckBoxMouseClick(object sender, MouseEventArgs e)
{
//MouseEventArgs me = (MouseEventArgs) e;
if (uxMouseCopyCheckBox.Checked)
{
MessageBox.Show("Test");
uxMouseCopyCheckBox.Checked = false;
}
}
I have searched the stack overflow and Google and found similar items but not in C# but no luck on the fixed solution. What I want to do it use the first click to change the check box to true without triggering the mouse click event. I want to delay the event to the 2nd mouse click and not the first.
I have tried the following:
for loop
Clicks == 2 with if statement
subscribing but at a loss on what to use
Instead of the Click event you could subsribe to the CheckedChanged event :
The Handler will look look exactly like yours :
private void uxMouseCopyCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (!uxMouseCopyCheckBox.Checked)
{
MessageBox.Show("Test");
uxMouseCopyCheckBox.Checked = false;
}
}
The only difference is that we want the Message box to be shwon only on the second click so when you will uncheck the checkbox.
Be careful though, if you change the default state of the checkbox, it will no longer work.
If you want a really robust solution Grant's one is IMHO the best, mine was just here to show you how to adapt your code for it to work
Just use a boolean variable as a flag.
private bool wasAlreadyClickedOnce;
private void uxCheckBoxMouseClick(object sender, MouseEventArgs e)
{
if (!wasAlreadyClickedOnce)
{
wasAlreadyClickedOnce = true;
return;
}
if (uxMouseCopyCheckBox.Checked)
{
MessageBox.Show("Test");
uxMouseCopyCheckBox.Checked = false;
}
}
Try using the Click event instead of CheckedChanged event to check or uncheck the CheckBox and then you can use the MouseClick event for other stuff.

How to detect if Enter event triggered by DropDown event for a ComboBox (c#)

I want my combobox's dropdown list to be shown with combobox enter event. That's easy just by adding cmb_box.DroppedDown = true; in the Enter event, i know but if the user opens the list by clicking the arrow button, the list pops up then closes itself. I tried adding
if (!cmb_box.DroppedDown) cmb_box.DroppedDown = true;
but didn't help. I even tried to define a global var to set it true on DropDown event and false on DropDownClosed event and check it in Enter event but that didn't work either. So i guess i need to detect if Enter event triggered by DropDown event in Enter method. Is that possible?
Better you can write like this
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')//Enter Key
{
cmb_box.Focus();
cmb_box.DroppedDown = true;
}
}
textBox4 is the control before the combobox(cmb_box) control

How to handle WinForms control click event when it's not a double click

I need to differentiate between a single click and a double click but I need to do this during the click event. I need this because if there's a single click I want to call Function A and if there's a double click I want to call Function B. But Function A must be called only in case of a single click.
How may I achieve this using standard Winforms in C# (or VB)?
click and double click can be handled seperately
click -> http://msdn.microsoft.com/en-US/library/system.windows.forms.control.click(v=vs.80).aspx
double click -> http://msdn.microsoft.com/en-US/library/system.windows.forms.button.doubleclick(v=vs.80).aspx
You will need to use a timer wait "some amount of time" after the click event to determine if the click was a single click. You can use the SystemInformation.DoubleClickTime property to determine the maximum interval between clicks that the system will consider sequential clicks a double click. You would probably want to add a little padding to this.
In your click handler, increment a click counter and start the timer. In the double click handler, set a flag to denote a double click occurred. In the timer handler, check to see if the double click event was raised. If not, it was a single click.
Something like this:
private bool _doubleClicked = false;
private Timer _clickTrackingTimer =
new Timer(SystemInformation.DoubleClickTimer + 100);
private void ClickHandler(object sender, EventArgs e)
{
_clickTrackingTimer.Start();
}
private void DoubleClickHandler(object sender, EventArgs e)
{
_doubleClicked = true;
}
private void TimerTickHandler(object sender, EventArgs e)
{
_clickTrackingTimer.Stop();
if (!_doubleClicked)
{
// single click!
}
_doubleClicked = false;
}
Another options is to create a custom control which derives from Button, and then call the SetStyles() method, which is a protected method) in the constructor and set the ControlStyles flag
class DoubleClickButton : Button
{
public DoubleClickButton() : base()
{
SetStyle(ControlStyles.StandardDoubleClick, true);
}
}

ListView ItemChanged puzzle with MessageBoxes - ItemSelectionChanged called twice

Here is the problem: I have a Windows Forms application that I'm developing, and in one segment I'm using a ListView control.
What I'm trying can be simply stated as: on event ListViewItemSelectionChange show a MessageBox for user to confirm the change, if not confirmed change to let's say the first item. This change to the first item would again fire ListViewItemSelecionChange, so I unregister and re-register the event handler method, so everything should be good, right?
What actually happens is that the handler method is called twice (actually ListView should fire two events on Selection change, one for deselect, other for newly selected item, but I have an e.IsSelected statement at the beginning to catch only selected items, so actually you could say that there are four events fired).
The problem is, if I generated the first event with mouse click on ListView item, and I've unsubscribed before programatically changing to the first item, what generates the second event firing? Is it some focus change because of the MessageBox call? Is there any way to prevent the second event to fire?
I have a simple example solution here, it can't be more simlified (25 SLOC), so if you can, please take a look. Note that commenting the line "if (ShowMessageBox())" stops the second event from firing, is this some focus change problem?
http://www.filedropper.com/listviewtestwithmsgbox
Edit: the relevant code:
private void listViewWithSelection1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
// listview actually generates two ItemSelectionChanged events,
// one for deselect of a item, and another event for a newly selected item (which we want here).
if (e.IsSelected)
{
if (ShowMessageBox())
Button1_Click(null, EventArgs.Empty);
label1.Text += "item selected ";
}
}
private bool ShowMessageBox()
{
return MessageBox.Show("Change to first item instead?", "test", MessageBoxButtons.YesNo) == DialogResult.Yes;
}
private void Button1_Click(object sender, EventArgs e)
{
// change ti first ListView item
listView1.ItemSelectionChanged -= listViewWithSelection1_ItemSelectionChanged;
listView1.Items[0].Selected = true;
listView1.ItemSelectionChanged += listViewWithSelection1_ItemSelectionChanged;
}
Hmm, can you describe how the selection is being changed to begin with? If it's by the user clicking to select an item, perhaps catch the Click or DoubleClick event rather than the ItemSelectionChanged event? I have this snippet I'm using on a program currently. If the user double clicks the list box (listView, in your case), do something with the selected item.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool ShowMessageBox()
{
return MessageBox.Show("Change to first item instead?", "test", MessageBoxButtons.YesNo) == DialogResult.Yes;
}
private void listView1_Click(object sender, EventArgs e)
{
if (ShowMessageBox())
listView1.TopItem.Selected = true;
label1.Text += "item selected ";
}
}
Edited to include relevant code.
One way to do this is to have a flag which says should the on change code run.
In your ListViewItemSelecionChange code you check the value of the flag and run code accordingly.

Categories