C#窗体使用API模拟键盘输出

代码如下:


        [DllImport("user32.dll", EntryPoint = "keybd_event", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern void keybd_event(byte vk, byte scan, int flags, int extrainfo);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern short VkKeyScan(char key);

        private byte vk_Shift = 0x10;

        public void PutChr(string putstr)
        {
            putstr += "\r\n";
            for (int tmp = 0; tmp < putstr.Length; tmp++)
            {
                if (VkKeyScan(putstr[tmp]) > 256)
                {
                    keybd_event(vk_Shift, 0, 0, 0);
                    keybd_event(Convert.ToByte(putstr[tmp]), 0, 0, 0);
                    keybd_event(Convert.ToByte(putstr[tmp]), 0, 2, 0);
                    keybd_event(vk_Shift, 0, 2, 0);
                }
                else
                {
                    keybd_event((byte)VkKeyScan(putstr[tmp]), 0, 0, 0);
                    keybd_event((byte)VkKeyScan(putstr[tmp]), 0, 2, 0);
                }
            }
        }

调用模拟键盘输出:

//调用API模拟键盘输出
  TextBox1.Focus();
            PutChr("你需要输出的内容"+"\r\n");

 

你可能感兴趣的:(C#窗体)