1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class ClipboardMonitor : IDisposable
{
#region P/Invoke
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
#endregion
#region Constante
private const int WM_DRAWCLIPBOARD = 0x0308;
private const int WM_CHANGECBCHAIN = 0x030D;
#endregion
#region Private Fields
private IntPtr Handle = IntPtr.Zero;
private IntPtr ClipboardViewerNext = IntPtr.Zero;
private Boolean Enabled = false;
#endregion
#region Properties
public Boolean IsEnabled
{
get
{
return (this.Enabled);
}
set
{
this.Enabled = value;
}
}
#endregion
#region Event
public event ClipboardChangedEventHandler ClipboardChanged = null;
#endregion
#region Methods
public void Start()
{
this.Enabled = true;
}
public void Stop()
{
this.Enabled = false;
}
public bool FilterMessage(ref Message m)
{
if (!this.Enabled)
{
return false;
}
switch (m.Msg)
{
case WM_DRAWCLIPBOARD:
if (this.ClipboardChanged != null)
{
try
{
System.Windows.IDataObject IData = System.Windows.Clipboard.GetDataObject();
this.ClipboardChanged(this, new ClipboardChangedEventArgs(IData));
}
catch
{
}
}
SendMessage(this.ClipboardViewerNext, m.Msg, m.WParam, m.LParam);
return (true);
case WM_CHANGECBCHAIN:
if (m.WParam == this.ClipboardViewerNext)
{
this.ClipboardViewerNext = m.LParam;
}
else
{
SendMessage(this.ClipboardViewerNext, m.Msg, m.WParam, m.LParam);
}
return (true);
default:
return (false);
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
ChangeClipboardChain(this.Handle, this.ClipboardViewerNext);
this.Handle = IntPtr.Zero;
this.ClipboardViewerNext = IntPtr.Zero;
}
#endregion
#region Constructor
public ClipboardMonitor()
{
Process P = Process.GetCurrentProcess();
this.Handle = P.MainWindowHandle;
this.ClipboardViewerNext = SetClipboardViewer(this.Handle);
}
#endregion
#region Singleton
private static ClipboardMonitor Singleton = null;
public static ClipboardMonitor Instance
{
get
{
if (Singleton == null)
Singleton = new ClipboardMonitor();
return (Singleton);
}
}
#endregion |
Partager