Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect control + v for pasting

Tags:

c#

wpf

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?

like image 488
Abdullah Khan Avatar asked Mar 16 '23 02:03

Abdullah Khan


1 Answers

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))
            {

            }
        }
    }
}
like image 109
Jakob Avatar answered Mar 28 '23 09:03

Jakob