ai写了一个,还是乱码。。。
粘到WPS里面都没啥问题,粘到excel里面就乱码,麻了
 - // Win32 API常量
- private const uint CF_TEXT = 1;
- private static readonly uint CF_HTML = RegisterClipboardFormat("HTML Format");
- // Win32 API函数
- [DllImport("user32.dll")]
- private static extern bool OpenClipboard(IntPtr hWndNewOwner);
- [DllImport("user32.dll")]
- private static extern bool CloseClipboard();
- [DllImport("user32.dll")]
- private static extern bool EmptyClipboard();
- [DllImport("user32.dll")]
- private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
- [DllImport("kernel32.dll")]
- private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes);
- [DllImport("kernel32.dll")]
- private static extern IntPtr GlobalLock(IntPtr hMem);
- [DllImport("kernel32.dll")]
- private static extern bool GlobalUnlock(IntPtr hMem);
- [DllImport("kernel32.dll")]
- private static extern uint RegisterClipboardFormat(string lpszFormat);
- public static void WriteToClipboard(string html,string text)
- {
- // 打开剪贴板
- if (OpenClipboard(IntPtr.Zero))
- {
- try
- {
- // 清空剪贴板
- EmptyClipboard();
- // 写入HTML格式
- if (!string.IsNullOrEmpty(html))
- {
- SetClipboardText(html, CF_HTML);
- }
- // 写入纯文本格式
- if (!string.IsNullOrEmpty(text))
- {
- SetClipboardText(text, CF_TEXT);
- }
- }
- finally
- {
- // 确保关闭剪贴板
- CloseClipboard();
- }
- }
- }
- private static void SetClipboardText(string text, uint format)
- {
- // 分配全局内存
- IntPtr hGlobal = GlobalAlloc(0x2000, (UIntPtr)(text.Length + 1));
- if (hGlobal != IntPtr.Zero)
- {
- try
- {
- // 锁定内存并复制数据
- IntPtr pGlobal = GlobalLock(hGlobal);
- if (pGlobal != IntPtr.Zero)
- {
- byte[] bytes = Encoding.UTF8.GetBytes(text);
- Marshal.Copy(bytes, 0, pGlobal, bytes.Length);
- Marshal.WriteByte(pGlobal + bytes.Length, 0); // 添加null终止符
- GlobalUnlock(pGlobal);
- // 设置剪贴板数据
- SetClipboardData(format, hGlobal);
- }
- }
- catch
- {
- // 发生错误时释放内存
- Marshal.FreeHGlobal(hGlobal);
- throw;
- }
- }
- }
|