I am new to C#. I am using the following code to detect Ctrl+v when pressed on the keyboard:
while(true)
{
bool check = (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl));
if (check && Keyboard.IsKeyDown(Key.V))
{
if (Clipboard.ContainsText())
history.Dispatcher.Invoke(new invoke_method2(update2),
new object[] { Clipboard.GetText(), history });
}
}
The program is running in the background. The problem is, it works when the user presses Ctrl and then v. But the conditions also stand true if the user presses v and then Ctrl, which is an unwanted trigger. Is there a way to overcome it?
To capture a shortcut in a window in WPF, implement a KeyDown event, so creating a new thread isn't necessary:
public MainWindow()
{
InitializeComponent();
KeyDown += MainWindow_KeyDown;
}
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
if (e.Key == Key.V)
{
}
}
}
Edit:
If you want to go with your solution, then you're practically searching for a point in time when V isn't pressed, but Ctrl is, so the following works:
while (true)
{
if (!Keyboard.IsKeyDown(Key.V))
{
while (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (Keyboard.IsKeyDown(Key.V))
{
}
}
}
}
Related
When the suggestion list is open, the up/down arrow keys automatically fires the SuggestionChosen event. I am wondering if there is a way to intercept this key press? I have tried to use the KeyDown and KeyUp events to catch these key presses but the SuggestionChosen event occurs before the KeyDown/Up events. This effectively forces the user to choose either the first or the last suggestion on the list. Mouse click or touch selection is fine.
I would just like to ignore the arrow keys while typing in the AutoSuggestBox. Or, not force the user to choose the first or last items with the arrow keys. Is there any way to accomplish this? Thank you
XAML
<AutoSuggestBox Name="EmailSuggestBox"
PlaceholderText="Email"
Text="{Binding Customer.EmailAddress, Mode=TwoWay}"
TextChanged="EmailSuggestBox_TextChanged"
QuerySubmitted="EmailSuggestBox_QuerySubmitted"
SuggestionChosen="EmailSuggestBox_SuggestionChosen"
LostFocus="EmailSuggestBox_LostFocus"
KeyUp="EmailSuggestBox_KeyUp"
KeyDown="EmailSuggestBox_KeyDown" />
Methods (Note: vm.EmailOptions is just a list of email domain suggestions)
private void EmailSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
try
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
if (sender.Text.Contains('#'))
{
var vm = this.DataContext as ProspectInformationEntryViewModel;
var d = sender.Text.Split('#');
var domain = d.LastOrDefault();
List<String> _emailSuggestion = vm.EmailOptions.Where(x => x.StartsWith(domain)).ToList();
sender.ItemsSource = _emailSuggestion;
}
}
}
catch (Exception)
{ }
}
private void EmailSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
try
{
if (args.ChosenSuggestion != null)
{
sender.ItemsSource = null;
}
}
catch (Exception)
{ }
}
private void EmailSuggestBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
try
{
var domain = args.SelectedItem.ToString();
var temp = sender.Text.Split('#');
var identifier = temp.FirstOrDefault();
sender.Text = identifier + "#" + domain;
sender.ItemsSource = null;
}
catch (Exception)
{ }
}
private void EmailSuggestBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Down || e.Key == Windows.System.VirtualKey.Up)
{
e.Handled = true;
}
}
private void EmailSuggestBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Down || e.Key == Windows.System.VirtualKey.Up)
{
e.Handled = true;
}
}
I would just like to ignore the arrow keys while typing in the AutoSuggestBox.
For your requirement, you could use ProcessKeyboardAccelerators event to intercept keydown or keyup press.
private void Autosbox_ProcessKeyboardAccelerators(UIElement sender, ProcessKeyboardAcceleratorEventArgs args)
{
if (args.Key == VirtualKey.Down || args.Key == VirtualKey.Up)
{
args.Handled = true;
}
}
Override the ToString() on your object will do the trick
I have this
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
var items = new[] { 500+ objects here };
if (toolStripTextBox1.Text.StartsWith("www."))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("http://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("https://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (items.Any(item => toolStripTextBox1.Text.Contains(item)))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
else
{
webBrowser1.Navigate("https://www.google.ca/?gws_rd=ssl#safe=active&q=" + toolStripTextBox1);
}
}
}
and it litteraly doesn't work. eg. I run it, no errors, all it does is play the windows error sound and won't be functional....
I know the code after the if statement is functional cause i have the exact same code on a button and it works just fine.
Use your code in key up event, not key down, this will make event fully executed and eligible to read the key pressed.
I have adjusted your code and it works, you don't have to use KeyChar just use KeyCode instead and it should work.
private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter || e.KeyValue == (char)Keys.Return)
//if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
var items = new[] { 500 + "objects here" };
if (toolStripTextBox1.Text.StartsWith("www."))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("http://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("https://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (items.Any(item => toolStripTextBox1.Text.Contains(item)))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
else
{
webBrowser1.Navigate("https://www.google.ca/?gws_rd=ssl#safe=active&q=" + toolStripTextBox1);
}
}
Make sure that the control has focus, or redirect the event to the control
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown%28v=vs.110%29.aspx
Try this for your KeyPress event handler:
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
//Insert code here
It sounds like the problem may be that the method is not bound to the KeyPress event.
In the designer, click on the textbox, and then over to the side where it lists all of the properties, there should be a lightning bolt looking icon, click on that, and then scroll down to KeyPress and make sure it says toolStripTextBox1_KeyPress
EDIT
Alternatively, you can add the event handler programmatically. In your Form_Load event, add the code
toolStripTextBox1.KeyPress += toolStripTextBox1_KeyPress;
and in your Form_Closed event handler, add
toolStripTextBox1.KeyPress -= toolStripTextBox1_KeyPress;
I am trying to notify the user when some Keys are pressed. If Caps, Num, Scroll and Insert are pressed, the relative BarStaticItem (the application uses some devexpress controls) changes color to White.
void DxMainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.CapsLock)
{
if (e.KeyboardDevice.IsKeyToggled(Key.CapsLock))
{
bCaps.Tag = new SolidColorBrush(Colors.White);
}
else
{
bCaps.Tag = new SolidColorBrush(Colors.DarkGray);
}
}
if (e.Key == Key.NumLock)
{
if (e.KeyboardDevice.IsKeyToggled(Key.NumLock))
{
bNum.Tag = new SolidColorBrush(Colors.White);
}
else
{
bNum.Tag = new SolidColorBrush(Colors.DarkGray);
}
}
if (e.Key == Key.Scroll)
{
if (e.KeyboardDevice.IsKeyToggled(Key.Scroll))
{
bScrl.Tag = new SolidColorBrush(Colors.White);
}
else
{
bScrl.Tag = new SolidColorBrush(Colors.DarkGray);
}
}
if (e.Key == Key.Insert)
{
if (e.KeyboardDevice.IsKeyToggled(Key.Insert))
{
bIns.Tag = new SolidColorBrush(Colors.White);
}
else
{
bIns.Tag = new SolidColorBrush(Colors.DarkGray);
}
}
}
Everything works fine but when i press Insert inside a TextBox it does not work. The weird thing is that in dispute of the other KeyEvents the event for Insert is like never happening (breakpoint does not break), even if the functionality works fine (overwrite text when pressed etc).
Can someone explain me why?
Thanks.
The Insert key is handled by the TextBox control, so that the event is not routed up the UI element tree.
You may however attach a handler for the PreviewKeyDown event instead of KeyDown:
<Window ... PreviewKeyDown="DxMainWindow_KeyDown">
Please refer to the Routed Events Overview article on MSDN for more details.
I want to make a program to simulate textentry if user press the keys "D1 - D0" and simulate some numbers if user pressed the function keys..
Here is the code I have tried.
if (e.KeyData == Keys.D1){
SendKeys.Send("simulate this text entry");
}
if (e.KeyData == Keys.F12){
SendKeys.Send("123");
}
But the problem is when I press the F12 button, the KeyDown event identify the first "1" as the "D1" key and sends both "123" and "simulate this text entry"
How can I prevent this problem ?
When you go to send the keys, you'd have to set a flag so you know to ignore the characters being sent. Additionally, you'd need to know when to turn the flag back on. This could be done by setting a variable to the length of the value being sent, and then incrementing a counter with each detected key. This isn't foolproof as the user could hit keys in rapid succession (or hold a key down) and you wouldn't know if the keypress was a result of user interaction or from your simulation.
Here's the basic idea:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool IgnoreKeys = false;
private int target = 0;
private int counter = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!IgnoreKeys)
{
if (e.KeyData == Keys.D1)
{
Send("simulate this text entry");
}
if (e.KeyData == Keys.F12)
{
Send("123");
}
}
else
{
counter++;
if (counter == target)
{
IgnoreKeys = false;
}
}
}
private void Send(string entry)
{
IgnoreKeys = true;
counter = 0;
target = entry.Length;
SendKeys.Send(entry);
}
}
The problem is that using SendKeys.Send( ... ) there is no way your program can tell the difference between your sent keys and the user's keyboard input.
When you send the keys "123" it is the same as if the user pressed the 1, 2, and 3 keys.
Because you're listening for the 1 key, that event fires and catches the '1' sent by sendkeys.
If possible, try to append text to the content you're trying to "simulate textentry" into and avoid sendkeys.
Otherwise consider making your number hotkeys alt/ctrl-combinations such as this:
if (e.Control && e.KeyCode == Keys.D1)
{
SendKeys.Send("simulate this text entry");
e.Handled = true;
}
That will prevent this event from being fired when you press F12 and send "123" (because ctrl is not pushed).
Finally solved the problem.. :) Here is the code.. Have to use "SendKeys.Flush()" in this task...
private bool IgnoreKeys = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyData == Keys.D1) && (!IgnoreKeys))
{
SendKeys.Send("Simulate this text" + "{ENTER}");
}
if (e.KeyData == Keys.F12)
{
IgnoreKeys = true;
SendKeys.Send("123");
SendKeys.Flush();
IgnoreKeys = false;
}
This prevents the KeyDown event considering "1" in the text "123" as the key "D1"
Idea is Idle_Mind's :) Thank you..
In a WPF application, i have a window that has a lot of fields.
When the user uses the TAB key after filling each field, windows understands that it moves on to the next. This is pretty know behavior.
Now what I want to to, is make it simulate the TAB key, when in fact the RETURN gets hit.
So in my WPF xaml I added imply KeyDown="userPressEnter"
And in the code behind it:
private void userPressEnter(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
e.Key = Key.Tab // THIS IS NOT WORKING
}
}
Now, obviously this is not working. But what I don't know is, how DO I make this work?
EDIT 1 ==> FOUND A SOLUTION
I found something that helped me out =)
private void userPressEnter(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
MoveFocus(request);
}
}
This way the Focus moves on the the next it can find :)
You can look at a post here:
http://social.msdn.microsoft.com/Forums/en/wpf/thread/c85892ca-08e3-40ca-ae9f-23396df6f3bd
Here's an example:
private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
request.Wrapped = true;
((TextBox)sender).MoveFocus(request);
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
System.Diagnostics.Debug.WriteLine(keyData.ToString());
switch (keyData)
{
case Keys.Enter:
SendKeys.Send("{TAB}");
break;
}
base.ProcessDialogKey(keyData);
return false;
}
How about make SendKeys Class Working like Winforms.SendKeys
https://michlg.wordpress.com/2013/02/05/wpf-send-keys/
public static class SendKeys
{
public static void Send(Key key)
{
if (Keyboard.PrimaryDevice != null) {
if (Keyboard.PrimaryDevice.ActiveSource != null) {
var e1 = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key) { RoutedEvent = Keyboard.KeyDownEvent };
InputManager.Current.ProcessInput(e1);
}
}
}
}
I think you should use that to simulate TAB :
SendKeys.Send("{TAB}");
Instead of
e.Key = Key.Tab
Sources : http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx
SendKeys.Send or SendKeys.SendWait will not work in a WPF application, so to answer the original question
if (e.Key == Key.Return)
{
KeyEventArgs tabPressEventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent };
InputManager.Current.ProcessInput(tabPressEventArgs);
}
Use Method SelectNextControl of your Form
I think the best solution is:
var ue = e.OriginalSource as FrameworkElement;
if (e.Key == Key.Return)
{
e.Handled = true;
ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}