-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClipboardMonitor.cs
More file actions
74 lines (64 loc) · 2.18 KB
/
Copy pathClipboardMonitor.cs
File metadata and controls
74 lines (64 loc) · 2.18 KB
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
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace CopyAlert
{
public class ClipboardMonitor : IDisposable
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AddClipboardFormatListener(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
private const int WM_CLIPBOARDUPDATE = 0x031D;
private Window _window;
private HwndSource? _hwndSource;
public event EventHandler? ClipboardUpdate;
public ClipboardMonitor(Window window)
{
_window = window;
_window.SourceInitialized += Window_SourceInitialized;
// If the window is already initialized, hook it now
if (_window.IsLoaded)
{
InitializeHook();
}
}
private void Window_SourceInitialized(object? sender, EventArgs e)
{
InitializeHook();
}
private void InitializeHook()
{
if (_hwndSource == null)
{
_hwndSource = PresentationSource.FromVisual(_window) as HwndSource;
if (_hwndSource != null)
{
_hwndSource.AddHook(HwndHook);
AddClipboardFormatListener(_hwndSource.Handle);
}
}
}
private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_CLIPBOARDUPDATE)
{
ClipboardUpdate?.Invoke(this, EventArgs.Empty);
}
return IntPtr.Zero;
}
public void Dispose()
{
if (_hwndSource != null)
{
RemoveClipboardFormatListener(_hwndSource.Handle);
_hwndSource.RemoveHook(HwndHook);
_hwndSource = null;
}
_window.SourceInitialized -= Window_SourceInitialized;
}
}
}