I have the following code
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
class Program
{
static string originalClipboardContent;
static KeyboardHook hook = new KeyboardHook();
[DllImport("user32.dll")]
public static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
public static extern bool CloseClipboard();
[DllImport("user32.dll")]
public static extern bool EmptyClipboard();
[DllImport("user32.dll")]
public static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);
[DllImport("user32.dll")]
public static extern IntPtr GetClipboardData(uint uFormat);
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
[STAThread]
static void Main()
{
hook.KeyPressed += hotkey_Pressed;
// Do not delve into the implementation of KeyBoardHook class, the event is called by pressing the keys and the handler method is called
hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt,
Keys.Up);
NotifyIcon icon = new NotifyIcon();
icon.Icon = SystemIcons.Application;
icon.Text = "Clipboard Manager";
icon.Visible = true;
Application.Run();
icon.Dispose();
}
static void GetClipBoardText(out string strs)
{
OpenClipboard(IntPtr.Zero);
strs = Marshal.PtrToStringUni(GetClipboardData(13));
CloseClipboard();
}
static void SetClipBoardText(string s)
{
OpenClipboard(IntPtr.Zero);
EmptyClipboard();
IntPtr textPtr = Marshal.StringToHGlobalUni(s);
SetClipboardData(13, textPtr);
CloseClipboard();
}
static void hotkey_Pressed(object sender, EventArgs e)
{
GetClipBoardText(out originalClipboardContent);
SendKeys.SendWait("^(INS)");
string selected;
GetClipBoardText(out selected);
using (StreamWriter writer = new StreamWriter("selected_text.txt"))
{
writer.WriteLine(selected);
}
SetClipBoardText(originalClipboardContent);
}
}
When I press ctrl+alt+up, the method that handles this hotkey, to my surprise, does not call Ctrl+Insert and the logic I need does not work. I have tried various techniques including keybd_event from user32.dll , ctrl+c instead of ctrl+insert but none of that helped. What is the problem? Is it related to window protection?: