C# API复制/拷贝到剪辑板

昨天在做一个程序的时候需要用到”剪辑板”功能, 可是死活引用不了”windows.forms”… (忘记添加引用了)

无奈只好去找了一个易语言的”置剪辑板文本”, 来翻译.

#代码

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
/// <summary>
/// 复制字符串到剪辑板
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
static bool CopyString(string text)
{
int DwLength = text.Length+1;
int GHND = 2;
int hGlobalMemory = GlobalAlloc(GHND, DwLength);
int lpGlobalMemory = GlobalLock(hGlobalMemory);

RtlMoveMemory(lpGlobalMemory, text, DwLength);
GlobalUnlock(hGlobalMemory);

int hWnd=0;
OpenClipboard(hWnd);
EmptyClipboard();

const int CF_TEXT = 1;
bool i;
if (SetClipboardData(CF_TEXT, hGlobalMemory) != 0)
{
i = true;
}
else
{
i = false;
}
CloseClipboard();
return i;
}

//全局堆栈分配_
[DllImport("kernel32.dll")]
static extern int GlobalAlloc(int wFlags, int dwBytes);

//锁住全局内存块_
[DllImport("kernel32.dll")]
static extern int GlobalLock(int hMem);

//拷贝内存
[DllImport("kernel32.dll")]
static extern int RtlMoveMemory(int 目标地址, string 源数据, int 尺寸);

//解锁全局内存块
[DllImport("kernel32.dll")]
static extern int GlobalUnlock(int hMem);

//清空剪辑板
[DllImport("user32.dll")]
static extern int EmptyClipboard();

//打开剪辑板
[DllImport("user32.dll")]
static extern int OpenClipboard(int 剪辑板句柄);

//设置剪辑板数据
[DllImport("user32.dll")]
static extern int SetClipboardData(int wFormat, int hMem);

//关闭剪辑板
[DllImport("user32.dll")]
static extern int CloseClipboard();


C# API复制/拷贝到剪辑板
http://edk24.com/2017/e4307f35.html
作者
余小波
发布于
2017年12月24日
许可协议