1. 程式人生 > >C# API複製/拷貝到剪輯板

C# API複製/拷貝到剪輯板

備忘

昨天在做一個程式的時候需要用到”剪輯板”功能, 可是死活引用不了”windows.forms”… (忘記新增引用了)

無奈只好去找了一個易語言的”置剪輯板文字”, 來翻譯.

程式碼

      /// <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();