C# simulating Ctrl+C using Win API keybd_event after Accessing clipboard shuts the program without an exception

-1

In my application I want to get the currently selected text. To do that, I simulate A Ctrl+C keystroke using the function SendCtrlC() and then recieve the selected text from the Clipboard using the function GetClipText().

After I have called these two functions, the application crashes in SendCtrlC() after trying to keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0). In the output window:

The program '...' has exited with code -1073741510 (0xc000013a).

What could cause this problem? How Can I fix it?

SendCtrlC()

public static void SendCtrlC()
        {
            byte VK_LCONTROL = 0xA2;
            uint KEYEVENTF_KEYUP = 2;
            byte VK_C = 0x43;
            keybd_event(VK_LCONTROL, 0, 0, 0);
            keybd_event(VK_C, 0, 0, 0);
            keybd_event(VK_C, 0, KEYEVENTF_KEYUP, 0);
            keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);//this line shuts the program
        }

GetClipText()

public static string GetClipText()
        {
            if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
                return null;

            try
            {
                if (!OpenClipboard(IntPtr.Zero))
                    return null;

                IntPtr handle = GetClipboardData(CF_UNICODETEXT);
                if (handle == IntPtr.Zero)
                    return null;

                IntPtr pointer = IntPtr.Zero;

                try
                {
                    pointer = GlobalLock(handle);
                    if (pointer == IntPtr.Zero)
                        return null;

                    int size = GlobalSize(handle);
                    byte[] buff = new byte[size];

                    Marshal.Copy(pointer, buff, 0, size);

                    return Encoding.Unicode.GetString(buff).TrimEnd('\0');
                }
                finally
                {
                    if (pointer != IntPtr.Zero)
                        GlobalUnlock(handle);
                }
            }
            finally
            {
                CloseClipboard();
            }
        }

The same problem happens when using

c#
winapi
keyboard
sendkeys
asked on Stack Overflow May 21, 2020 by Tal XD

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0