How to tell if Shift is being pressed in a MouseDown event? - winforms

I am catching a MouseDown event on a control, which gives me a MouseEventArgs object in the signature. Now I want to be able to tell if the user was holding down the "Shift" or "Control" key when they clicked. But the MouseEventArgs object doesn't contain any keyboard information!
What's the easiest way of telling whether the keyboard Shift/Ctrl keys were being held at the time of the click?

Use the Control.ModifierKeys property to see what's pressed. For example:
private void Form1_MouseClick(object sender, MouseEventArgs e) {
if (Control.ModifierKeys == Keys.Control) {
Console.WriteLine("Ctrl+Click");
}
}
Other modifiers are Keys.Alt and Keys.Shift. Find combinations with, say, (Keys.Control | Keys.Shift).

In C#, you can check using -
Keyboard.IsKeyDown(Key.LeftShift) or key.RightShift
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.iskeydown.aspx
http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx

Related

Get Clipboard value from static variable

So a sequel to my last post...
I have PieChart with Legend and i want to be able to right click on Legend title and copy the value.
So this is the Legend Mouse Right click Event:
private void pieLegend_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var hoveredItem = this.pieLegend.Items.FirstOrDefault(x => x.IsHovered);
Clipboard.SetText(hoveredItem.Title);
}
As you can see i am copy the value the the Clipboard but i want to open simple Copy menu so i create ContextMenu and i have the ContextMenu Click Event:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
}
Not inside this Click Event i want to get the Clipboard but because pieLegend_MouseRightButtonDown event is fired before this Click Event i want to find a way to get this Clipboard value.
So i was thinking about create a Static variable that the first Event will set the Clipboard value and from the Click Event just get this value but my question is if this is the best way/appropriate way to do that.
Well, there's nothing wrong with doing both.
I think you are over thinking this, you really need to consider your requirements.
In this particular scenario, I would not suggest using the clipboard to transfer data from the two events. Why? Well, because the user can easily just copy something else onto their clipboard which may be completely unrelated to your application, therefore it could be erroneous.
So, I expect defining a private or static variable (This really depends on the scope, you don't need to define a static variable if you don't have to) is the correct way to go.
private string _HoveredItemTitle;
private void pieLegend_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var hoveredItem = this.pieLegend.Items.FirstOrDefault(x => x.IsHovered);
Clipboard.SetText(hoveredItem.Title);
_HoveredItemTitle = hoveredItem.Title;
}
And in your other method, it'd be a good idea to check if there is something in this variable, otherwise it may not be a good idea to go a head with the execution.
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(_HoveredItemTitle))
{
//TODO: Something useful
return;
}
//TODO
}
I think the main idea I'm trying to get across here is that you should ensure that there is nothing (or as little as possible) that the user can do to cause errors in your application. In this scenario, copying the text to the clipboard is nice, but it's more of a feature than a requirement. The application should not have to rely on the clipboard, simply because there might be complete nonsense on the clipboard, instead of the data that you are actually expecting.

How can I get more than one character to show in a messagebox from a textbox user input?

I have made a textbox and I want the user to type in a string of numbers and hit enter. I have setup the following:
private void textBox1_TextChanged(object sender, EventArgs e)
{
String UserBarcode;
Focus();
UserBarcode = Console.ReadLine();
MessageBox.Show(UserBarcode);
}
When I enter any key into the textbox, I get a message box with nothing in it. I want to have the program wait til it hears the enter key then display the contents of the textbox.
The Textbox.TextChanged event fires as soon as the text in the textbox is changed at all. If you want a message box with the full string, you probably want to consider using the Textbox.LostFocus event or a button's Click event.
So you could have something like (I'm taking a stab at this here, as I've used VB rather than C#)
private void textBox1_LostFocus(object sender, EventArgs e)
{
MessageBox.Show(sender.Text)
}
If you're using a button, the above function should work, but you'll want to substitute textBox1.Text for sender.Text.
Take a look at Focus and Validation Events
There are several events that you can handle, depending on your goals and how your application is designed. If you want to perform validation and/or are using data binding, you may want to go with handling the validating/validated events. By default data bindings update a bound property after OnValidating. If you use LostFocus and read the value from a bound object, instead of your control, you will get inconsistent results.
I was able to figure it out finally. For some reason when I manually entered the code I kept getting multiple random errors. I started a new Visual C # Windows Forms Application, Made a textbox, chose the keydown property and double clicked on it to have the program inject the code for the keydown function and then I filled in the if statement pointing to the enter key. The final code looks like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(textBox1.Text);
}
}

Can I determine which keyboard a key pressed is on?

Users of my application have a second keyboard with special function keys. Unfortunately, the keys are mapped to buttons such as F, G, F1 and so on. I would like to handle PreviewKeyDown and prevent any keys from these keyboards having an effect in normal controls such as TextBoxes.
In WPF, is there any way of determining which keyboard raised the event?
No, it is not possible directly in WPF.
using System.Windows.Input you could be able to achieve this by capturing the event that is fired in your code behind. Sample code below shows how this can be done in Textbox.
private void SampleTextbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete) // delete key is pressed
{
e.Handled = true; // Ignore key press
}
}

How to give an initial value to textBox?

I want my C# program to have initial values for its textboxes. For example, in one of the textboxes, it should say "Please enter your name".
When you click (or tabStop) on the textbox, the initial value should disappear and the user will be able to enter their input to the textbox.
I can do all this with click_event, but using this method the initial text would not have less opacity. How am I able to achieve this?
This is how I finally did it:
Boolean first_time_click = true;
private void Form1_Load(object sender, EventArgs e)
{
textBox1.ForeColor = System.Drawing.Color.Gray;
textBox1.Text = "Enter the Text";
}
private void For_First_Click()
{
if (first_time_click)
{
textBox1.Clear();
textBox1.ForeColor = textBox1.ForeColor = SystemColors.WindowText;
}
first_time_click = false;
}
private void textBox1_Click(object sender, EventArgs e)
{
For_First_Click();
}
I assume you are talking about winform (tabstop) you have to handle it within the event key-press. you can use the below code:
TextBox1.Select(0, TextBox1.Text.Length);
this will select the text and window will remove it for you as soon as the user start to typing
you can use the same code to have this behavior also for TabStop
All you need to do is set the Textbox's .Text property and use GotFocus event to clear the box when the person clicks (or tabs) into it to start typing.
Always remember that there are more ways than the mouse to navigate a form, so use the GotFocus event to determine when the user enters a control, and use the Validated event to determine when they've changed data and exited the control.
For this type of effect you need java script.Because java script provide you functionality of mouse hover and mouse out these are the functions which provide you the same functionality which u seeing in this page of search bar. If you need code reply me i can give you.

WPF Mousedown => No MouseLeave Event

I'm building a Windows Presentation Foundation control with Microsoft Blend.
When I leave my control by pressing the left-mouse-button, the MouseLeave-Event is not raised. Why not?
This is intended behaviour: When you are doing mousedown on a control and leaving the control, the control STILL retains its "capture" on the mouse, meaning the control won't fire the MouseLeave-Event. The Mouse-Leave Event instead will be fired, once the Mousebutton is released outside of the control.
To avoid this, you can simple tell your control NOT to capture the mouse at all:
private void ControlMouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
Control control = (Control) sender;
control.Capture = false; //release capture.
}
Now the MouseLeave Event will be fired even when moving out while a button is pressed.
If you need the Capture INSIDE the Control, you need to put in more effort:
Start tracking the mouseposition manually, when the mousekey is pressed
Compare the position with the Top, Left and Size Attributes of the control in question.
Decide whether you need to stop the control capturing your mouse or not.
public partial class Form1 : Form
{
private Point point;
private Boolean myCapture = false;
public Form1()
{
InitializeComponent();
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
myCapture = true;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (myCapture)
{
point = Cursor.Position;
if (!(point.X > button1.Left && point.X < button1.Left + button1.Size.Width && point.Y > button1.Top && point.Y < button1.Top + button1.Size.Height))
{
button1.Capture = false; //this will release the capture and trigger the MouseLeave event immediately.
myCapture = false;
}
}
}
private void button1_MouseLeave(object sender, EventArgs e)
{
MessageBox.Show("Mouse leaving");
}
}
of course you need to stop the own tracking ( myCapture=false;) on MouseUp. Forgot that one :)
When I don't get mouse events I expect I typically use Snoop to help me understand what is happening.
Here are a couple of links:
1- Snoop (a WPF utility)
2- CodePlex project for Snoop
And for completeness and historical reasons (not the bounty - it doesn't make sense having two duplicate questions - you should probably move it into one if not too late)...
I made a thorough solution using global mouse hook here (approach 2)
WPF: mouse leave event doesn't trigger with mouse down
And simplified its use - you can use it by binding to commands in your view-model - e.g.
my:Hooks.EnterCommand="{Binding EnterCommand}"
my:Hooks.LeaveCommand="{Binding LeaveCommand}"
my:Hooks.MouseMoveCommand="{Binding MoveCommand}"
...more details in there
Old question but I came across the same problem with a Button (MouseLeave does not fire while MouseDown because MouseDown Captures the Mouse...)
This is how I solved it anyway:
element.GotMouseCapture += element_MouseCaptured;
static void element_MouseCaptured(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
element.ReleaseMouseCapture();
}
Hope that helps someone looking for a quick fix :P

Resources