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))
{
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With