-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClipboardService.cs
58 lines (50 loc) · 1.48 KB
/
ClipboardService.cs
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
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace nwn2_Chatter
{
/// <summary>
/// Gets/Sets text per the Windows Clipboard.
/// </summary>
/// <remarks>https://stackoverflow.com/questions/39832057/using-windows-clipboard#answer-39833879</remarks>
static class ClipboardService
{
[DllImport("user32.dll")]
static extern IntPtr GetOpenClipboardWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
static extern bool CloseClipboard();
/// <summary>
/// Sets a <c>string</c> to the Windows Clipboard after ensuring that
/// the Clipboard's process has been released by other apps.
/// </summary>
/// <param name="clip">the text to set</param>
internal static void SetText(string clip)
{
if (GetOpenClipboardWindow() != IntPtr.Zero)
{
OpenClipboard(IntPtr.Zero);
CloseClipboard();
}
if (!String.IsNullOrEmpty(clip))
Clipboard.SetText(clip);
else
Clipboard.Clear();
}
/// <summary>
/// Gets a <c>string</c> from the Windows Clipboard after ensuring that
/// the Clipboard's process has been released by other apps.
/// </summary>
/// <returns>the Clipboard's text</returns>
internal static string GetText()
{
if (GetOpenClipboardWindow() != IntPtr.Zero)
{
OpenClipboard(IntPtr.Zero);
CloseClipboard();
}
return Clipboard.GetText(TextDataFormat.Text);
}
}
}