source: 2015/koodauskerho/JesseS/ClipboardListener.cs @ 10334

Revision 7067, 1.9 KB checked in by empaheik, 4 years ago (diff)
Line 
1using System;
2using System.Runtime.InteropServices;
3using System.Windows.Forms;
4
5public sealed class ClipboardListener
6{
7    private static ClipboardListener instance = new ClipboardListener();
8
9    public delegate void ClipboardUpdateHandler(string contents);
10
11    /// <summary>
12    /// Tapahtuu kun leikepöydän sisältö muuttuu
13    /// </summary>
14    public static event ClipboardUpdateHandler ClipboardUpdate;
15
16    private static NotificationForm _form = new NotificationForm();
17
18    private class NotificationForm : Form
19    {
20        public NotificationForm()
21        {
22            NativeMethods.SetParent(Handle, NativeMethods.HWND_MESSAGE);
23            NativeMethods.AddClipboardFormatListener(Handle);
24        }
25
26        protected override void WndProc(ref Message m)
27        {
28            if (m.Msg == NativeMethods.WM_CLIPBOARDUPDATE)
29            {
30                var contents = Clipboard.GetText();
31                var handler = ClipboardUpdate;
32                if (handler != null && contents.Length > 0)
33                {
34                    handler(contents);
35                }
36            }
37            base.WndProc(ref m);
38        }
39    }
40}
41
42internal static class NativeMethods
43{
44    // See http://msdn.microsoft.com/en-us/library/ms649021%28v=vs.85%29.aspx
45    public const int WM_CLIPBOARDUPDATE = 0x031D;
46    public static IntPtr HWND_MESSAGE = new IntPtr(-3);
47
48    // See http://msdn.microsoft.com/en-us/library/ms632599%28VS.85%29.aspx#message_only
49    [DllImport("user32.dll", SetLastError = true)]
50    [return: MarshalAs(UnmanagedType.Bool)]
51    public static extern bool AddClipboardFormatListener(IntPtr hwnd);
52
53    // See http://msdn.microsoft.com/en-us/library/ms633541%28v=vs.85%29.aspx
54    // See http://msdn.microsoft.com/en-us/library/ms649033%28VS.85%29.aspx
55    [DllImport("user32.dll", SetLastError = true)]
56    public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
57}
Note: See TracBrowser for help on using the repository browser.