C# 控制台程序實現 Ctrl + V 粘貼功能


  代碼主要分為兩部分,首先調用系統API注冊剪切板相關的事件,然后監控用戶的按鍵操作。完整代碼如下:

   class ClipBoard
    {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern Int32 IsClipboardFormatAvailable(uint format);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern Int32 OpenClipboard(IntPtr hWndNewOwner);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetClipboardData(uint uFormat);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern Int32 CloseClipboard();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern Int32 GlobalLock(IntPtr hMem);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern Int32 GlobalUnlock(IntPtr hMem);

        [DllImport("kernel32.dll")]
        public static extern UIntPtr GlobalSize(IntPtr hMem);

        const uint CF_TEXT = 1;

        /// <summary>
        /// 實現控制台自動粘貼板功能
        /// </summary>
        /// <returns></returns>
        public static string PasteTextFromClipboard()
        {
            string result = "";
            if (IsClipboardFormatAvailable(CF_TEXT) == 0)
            {
                return result;
            }
            if (OpenClipboard((IntPtr)0) == 0)
            {
                return result;
            }

            IntPtr hglb = GetClipboardData(CF_TEXT);
            if (hglb != (IntPtr)0)
            {
                UIntPtr size = GlobalSize(hglb);
                IntPtr s = (IntPtr)GlobalLock(hglb);
                byte[] buffer = new byte[(int)size];
                Marshal.Copy(s, buffer, 0, (int)size);
                if (s != null)
                {
                    result = ASCIIEncoding.ASCII.GetString(buffer);
                    GlobalUnlock(hglb);
                }
            }

            CloseClipboard();
            return result;
        }

        /// <summary>
        /// 監控用戶輸入的按鍵
        /// </summary>
        public void KeyPress()
        {
            ConsoleKeyInfo ki = Console.ReadKey(true);
            if ((ki.Key == ConsoleKey.V) && (ki.Modifiers == ConsoleModifiers.Control))
            {
                Console.WriteLine("Ctrl+V pressed");
                string s = ClipBoard.PasteTextFromClipboard();
                Console.WriteLine(s);
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM