C#全局剪贴板内容

时间:2017-01-16 09:21:06

标签: c# clipboard

我不确定我是否正确地使用这种c#形式。我想获取任何窗口上发生的任何ctrl + C事件的剪贴板内容。捕获全局剪贴板信息的正确方法是什么?

    namespace WindowsFormsApplication1
{
    public class copydata
    {
        public int entry;
        public string data;
    }

    public partial class Form1 : Form
    {
        // DLL libraries used to manage hotkeys
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        const int COPY_ACTION   = 1;
        const int TOGGLE_FORM   = 2;
        const int WM_HOTKEY = 0x0312;

        List<copydata> copies;
        int count;
        public Form1()
        {
            InitializeComponent();

            RegisterHotKey(this.Handle, COPY_ACTION, 2, Keys.C.GetHashCode());
            RegisterHotKey(this.Handle, TOGGLE_FORM, 6, Keys.L.GetHashCode());

            copies = new List<copydata>();
            count = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(listBox1.Items[listBox1.SelectedIndex].ToString());
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if(m.Msg == WM_HOTKEY)
            {
                if(m.WParam.ToInt32() == COPY_ACTION)
                {
                    string val = Clipboard.GetText();
                    ++count;
                    copies.Add(new copydata { entry = count, data = val });
                    this.listBox1.DisplayMember = "data";
                    this.listBox1.ValueMember = "entry";
                    this.listBox1.DataSource = copies;
                }

                if (m.WParam.ToInt32() == TOGGLE_FORM)
                {
                    if(!this.Visible)
                    {
                        this.Show();
                    }
                    else
                    {
                        this.Hide();
                    }
                }
            }
        }

    }
}

0 个答案:

没有答案