C#调用WinApi将字符串“abced”写入剪切板
时间: 2023-10-08 14:06:32 浏览: 86
你可以使用 Windows API 通过 C# 将字符串写入剪贴板。以下是一个示例代码:
```csharp
using System.Runtime.InteropServices;
public class ClipboardHelper
{
[DllImport("user32.dll", SetLastError = true)]
public static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
public static extern bool EmptyClipboard();
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern UIntPtr GlobalSize(IntPtr hMem);
private const uint CF_UNICODETEXT = 13;
public static void SetText(string text)
{
if (!OpenClipboard(IntPtr.Zero))
{
throw new System.ComponentModel.Win32Exception();
}
try
{
// 清空剪贴板
if (!EmptyClipboard())
{
throw new System.ComponentModel.Win32Exception();
}
// 分配全局内存,并锁定内存区域
int byteCount = (text.Length + 1) * 2; // 两个字节表示一个 Unicode 字符
IntPtr hGlobal = GlobalAlloc(0x2000, (UIntPtr)byteCount); // 0x2000 表示 GMEM_MOVEABLE
if (hGlobal == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception();
}
try
{
IntPtr lpMem = GlobalLock(hGlobal);
if (lpMem == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception();
}
try
{
// 将字符串复制到内存区域
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(text);
Marshal.Copy(bytes, 0, lpMem, bytes.Length);
// 将内存区域设置为剪贴板数据
if (SetClipboardData(CF_UNICODETEXT, hGlobal) == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception();
}
// 在 Unlock 前不要释放内存,因为 SetClipboardData 后剪贴板会接管内存的控制权
}
finally
{
GlobalUnlock(lpMem);
}
}
catch
{
GlobalFree(hGlobal);
throw;
}
}
finally
{
CloseClipboard();
}
}
}
```
在上述代码中,SetText() 方法使用 CF_UNICODETEXT 格式将字符串写入剪贴板。你可以调用 SetText("abced") 将字符串 "abced" 写入剪贴板。
阅读全文