React to Button.IsPressed WPF - c#

I'd like to have a TextBlock changed when the button is pressed, and then return to the previous state when the button is released.
It appears that RepeatButton is not a solution here, as it only reacts to itself being held and not released - and I need to know when it is released so that I can run a proper method to return TextBlock to its original state. Being desperate I also tried to loop while(button.IsPressed) (yeah, I know, awful idea :() but to no avail - the code would hang (as if IsPressed did not change to false after the button had been released).
Is there any way to achieve it? Thanks in advance.

Maybe not the cleanest way, but I decided to create multiple handlers to my button: Click, PointerPressed, PointerCancelled, PointerCaptureLost, PointerReleased. First two are for handling the button being pressed, while the last three are for handling the release. I used all three due to recommendation here:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.pointerreleased
This is because PointerReleased may sometimes be substituded by other events being fired at button release.

PreviewMouseDown and PreviewMouseUp seem to work fine, if you want both left and right click to have your desired effect:
public partial class MainWindow : Window
{
private string TextBlockPreviousState = "";
public MainWindow()
{
InitializeComponent();
ButtonStatusTextBlock.Text = "foo";
}
private void StoreAndUpdate()
{
TextBlockPreviousState = ButtonStatusTextBlock.Text;
ButtonStatusTextBlock.Text = "Button Down";
}
private void Restore()
{
ButtonStatusTextBlock.Text = TextBlockPreviousState;
}
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
StoreAndUpdate();
}
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
Restore();
}
}

Related

How to switch tabs with button in a TabControl?

I've watched a few tutorials online on how to change tabs using buttons but for some reason all the code I've tried doesn't work. I am currently running Microsoft Visual Studio 2017 and am trying to write some code for a button to change tabs.
I couldn't find any differences between my code and code shown in tutorials, so it may just be a Visual Studio setting that I haven't set up correctly to allow the button correctly, but I couldn't figure out if or where it may be.
Here's my current code:
//Element event handlers
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
tabControl.SelectedTab = DestSelect;
}
private void buttonGotoIntro_Click(object sender, EventArgs e)
{
tabControl.SelectedTab = Intro;
}
//An old computer-generated segment code for the previous button.
//When I try to remove it the computer gets mad at me.
private void GotoIntro_Click(object sender, EventArgs e)
{
}
Please confirm you have subscribed to the Click event for the buttons.
public Form1()
{
InitializeComponent();
buttonStart.Click += buttonStart_Click;
buttonGotoIntro.Click += buttonGotoIntro_Click;
}
Instead of 'tabControl.SelectedTab = DestSelect;" try instead the method 'tabControl.SelectTab(DestSelect);'
I read through this article to find your (hopefully) answer:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/2cf22896-c5bd-4a9b-ab61-34404b55ef01/how-to-jump-to-a-specific-tab-in-the-tabcontrol?forum=vbgeneral
I assume u want to select a tab when a different Button is clicked.
tabControl.SelectedIndex = [Index of tab to switch to];
Code should look like;
tabControl.SelectedIndex = feeTabIndex;
If this is not clear enough, tell me exactly what you want to do.

Button mouse over ForeColour change

To create a mouse over button I use this code
private void btnCreateAccount_MouseHover(object sender, EventArgs e)
{
btnCreateAccount.ForeColor = Color.Gold;
}
private void btnCreateAccount_MouseLeave(object sender, EventArgs e)
{
btnCreateAccount.ForeColor = Color.Black;
}
The mouse over button works however when I hover over the button there is a good at least 1 second delay. I would think that it should change colour as soon as the mouse is placed over the button and not with a (in my opinion) too long delay.
Is there any way of fixing that code by like refreshing the button or something along those lines? or perhaps someone has a code that works perfectly?
You are handling the Mouse Hover event. This will require the cursor to be still for a short while in order to fire.
The pause required for this event to be raised is specified in milliseconds by the MouseHoverTime property.
This is read only.
Normally if you want the colour to change immediately you should handle the Mouse Enter event:
private void btnCreateAccount_MouseEnter(object sender, EventArgs e)
{
btnCreateAccount.ForeColor = Color.Gold;
}

Windows 8 / XAML Double Tap event always preceded by Tap

I've got a button in an app. I want it to do different things depending on whether I tap it (pause an animation) or double-tap (restart the animation)
however, when I double-tap, it seems to fire the tap event first and then the double-tap in quick succession. Is there a way around this? Is this a known issue or am I making a rookie mistake?
Edit: For those asking, I'm using the Tapped and DoubleTapped events.
Give the some pause to single tab . If there is double tab occur then single tab event eliminated
bool singleTap;
private async void control_Tapped_1(object sender, TappedRoutedEventArgs e)
{
this.singleTap = true;
await Task.Delay(200);
if (this.singleTap)
{
// Single tab Method .
}
}
private void control_DoubleTapped_1(object sender, DoubleTappedRoutedEventArgs e)
{
this.singleTap = false;
// Double tab Method
}
You might want to consider letting it do both. Think about it like double clicking a folder in windows. Users will be used to something happening on the first click (highlighting the folder) and they will be expecting the double click to both highlight, then navigate.
All in all it seems like a design issue, not a technical one.
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern uint GetDoubleClickTime();
bool _singleTapped = false;
//Tapped event handler
private async void control_Tapped(object sender, TappedRoutedEventArgs e)
{
_singleTapped = true;
//var x = GetDoubleClickTime();
//GetDoubleClickTime() gets the maximum number of milliseconds that can elapse between a first click and a second click
await Task.Delay(TimeSpan.FromMilliseconds(GetDoubleClickTime()));
if (!_singleTapped)
{ return; }
//SingleTapped code
}
//DoubleTapped event handler
private async void control_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
_singleTapped = false;
//DoubleTapped code
}

Buttons in a Visual Studios form application

Sorry if this is a dumb question, I'm taking an intro to programming class and need a bit of help with this project I'm working on.
I'm trying to write an application that has about 30 buttons. One common thing I want is for all the buttons to turn yellow when clicked. If they're clicked a second time, they change back to the default color. right now I use the code:
private void btn_1_Click(object sender, EventArgs e)
{
btn_1.BackColor = Color.Yellow;
}
But that only turns the buttons yellow, I can't turn them "off" by clicking it a second time.
Also, when I'm creating these button events in VS2010, I end up with 30 different event handlers for each button..Is there a way to get them all to do the same thing without having to write all the repetitive code?
I'm guessing that I would have to write my own buttons class? How would I go about doing that? Do i need to create a class library which inherits Buttons?
Sorry for the noob questions. THanks
If every button has a specific action that needs to be performed, then yes, you need to have a click handler for each; however, you can encapsulate the common behavior in a single method.
For example:
private void btn_1_Click(object sender, EventArgs e)
{
ToggleColor((Button)sender);
//rest of the code specific to this button
}
private void ToggleColor (Button button)
{
if(button.Color==Color.Yellow;
button.Color=Color.Black;
else
button.Color=Color.Yellow;
}
Note that above code is not tested.
Now, if all the buttons do the same thing, you can just set the on click handlers for all of them to be btn_1_Click; for example.
private void btn_1_Click(object sender, EventArgs e)
{
if (btn_1.BackColor != Color.Yellow)
{
btn_1.BackColor = Color.Yellow
}
else
{
btn_1.BackColor = Color.Control;
}
}
this is switching default and yellow
If all buttons do the exact same thing you can assign the same event handler to all buttons (instead of btn_1_Click, btn_2_Click etc... you'd have btton_click) - you can select this handler in the properties of each button.
You don't have to write your own class. You can simply assign all your buttons to the same event handler, like this:
button1.Click += new EventHandler(myEventHandler);
button2.Click += new EventHandler(myEventHandler);
button3.Click += new EventHandler(myEventHandler);
button4.Click += new EventHandler(myEventHandler);
Just keep in mind that your event handler has this signature:
private void myEventHandler(object sender, EventArgs e)
By doing that, all your buttons, when clicked, will trigger the same method.
Now to control the color, what you can do is create a simple property on your form which would hold the last color applied. It could be an enum, then you could simply check its value and apply the other one to the buttons, like this:
// Declare your enum:
private enum Colors { Yellow, Default }
private Colors ActualColor = Colors.Default;
// Write your custom event handler:
private void myEventHandler(object sender, EventArgs e)
{
if (ActualColor == Colors.Default)
{
// Apply yellow to buttons
ActualColor = Colors.Yellow;
}
else
{
// Apply default
ActualColor = Colors.Default;
}
}
In order to keep track whether it is the 'second time' you press the button, you should declare a variable OUTSIDE the method, which indicates whether you already pressed the button or not.
For example:
public bool IsButtonYellow;
private void btn_1_Click(object sender, EventArgs e) {
if(!IsButtonYellow) {
btn.BackColor = Color.Yellow;
IsButtonYellow = true;
}
else {
btn.BackColor = Control.DefaultBackColor;
IsButtonYellow = false;
}
}
Yes:
Create your own button class
Inherit from Button
Implement the handler in your button class and you're done
You can do something simple like this:
public class MyButton : Button
{
private bool _buttonState;
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (_buttonState)
{
BackColor = Color.Yellow;
}
else
{
BackColor = Color.White;
}
}
}
Then in your code you can just create as many of these "MyButton" objects as you need, with no code repetition.
To make all buttons use the same event handler in VS2010:
Click once on a button to select it.
In the “properties” window: click on the “lightning” (=events).
Paste the first button’s event name (btn_1_Click) next to “Click”.
Do the same for every button.
As for changing the color:
See answer by killie01.
Good luck.

When you set Checked property in a RadioBox, can you suppress the CheckChanged event?

I'm new to C# and Windows Form but if I have a radiobutton and I call radiobutton1.Checked=true, is there a way for it to not fire the CheckedChange event? I want to distinguish between the user clicking on the radiobutton and me setting the radiobutton programmatically. Is this possible?
Stop trying to defeat the design of the CheckedChanged event. It's specifically supposed to include programmatic changes.
If you want user-triggered changes and not programmatic changes, use the Click event instead. (You may be thinking that you don't want to restrict yourself to mouse clicks, don't worry, there's a MouseClick event for that, Click includes keyboard changes as well.)
Here's a straightforward method of using the event when you feel like it.
private bool SuppressRadioButton1Event { get; set; }
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (!this.SuppressRadioButton1Event)
{
MessageBox.Show("Not suppressed!");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.SetRadioButton1(false);
}
private void SetRadioButton1(bool checkedOn)
{
this.SuppressRadioButton1Event = true;
radioButton1.Checked = checkedOn;
this.SuppressRadioButton1Event = false;
}
A very easy way:
public void radio_OnCheckChanged(object sender, EventArgs e)
{
RadioButton r = sender as RadioButton;
bool isUserChange = r.Tag.Equals(1);
if (isUserChange) blabla
else blabla
r.Tag = null;
}
public void MyMethod()
{
radio1.Tag = 1;
radio.Checked = true;
}
You can use any kind of flag which users can't do by their clicking.But you can do via your code.
Why should your code care who checked the radiobutton?
EDIT: There are ways around this (subclass, flag), but don't. The only "legit" reason I can think of for wanting this is to prevent some side-effect from happening when the value is initially (programatically) displayed, and even that is suspect. Rethink the side-effect, does it really belong on the change-event, or the commit?
More info one why/what would help. On the surface, this looks like a design error.
One (hackish) way to do it would be to subclass RadioButton and override the OnCheckChanged virtual method, suppressing the event if the Checked property has been set programmatically.
However, since radio-buttons belong to a group, the event always fires in pairs (oen for the uncheck, one for the check). You will therefore want to suppress the event for the entire group when you choose the selected button programmatically. Here's an example implementation:
public class CustomRadioButton : RadioButton
{
private bool _suppressCheckedEvent;
public void SetChecked(bool value, bool suppressCheckedEvent)
{
if (!suppressCheckedEvent)
Checked = value;
else
{
SetSupressModeForGroup(true);
Checked = value;
SetSupressModeForGroup(false);
}
}
private void SetSupressModeForGroup(bool suppressCheckedEvent)
{
foreach (var crb in Parent.Controls.OfType<CustomRadioButton>())
crb._suppressCheckedEvent = suppressCheckedEvent;
}
protected override void OnCheckedChanged(EventArgs e)
{
if (!_suppressCheckedEvent)
base.OnCheckedChanged(e);
}
}
In this implementation, changing the checked-state through the Checked property will always fire the event. When you call the SetChecked method, you have the choice to suppress the event.
You could try to attach the event programmatically. Based on my application configuration I check several radio buttons but I don't want to fire events.
To attach an event programmatically:
chbOptionX.CheckedChanged += new System.EventHandler(this.chbShowStockBySizeAndColor_CheckedChanged);

Categories

Resources