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

備忘

昨天在作一個程序的時候須要用到」剪輯板」功能, 但是死活引用不了」windows.forms」… (忘記添加引用了)windows

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

代碼

/// <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();
相關文章
相關標籤/搜索