C#向光标处输入文字

1.开始的时候想用Clipboard,放弃没用

2.尝试一下第二种方式:

      1)新建SendMsg.cs

      2)将下面代码粘贴进去,修改namespace即可,绝对能用,不能用请留言:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace RFID
{
    [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            int left;
            int top;
            int right;
            int bottom;
        }
    public class SendMsg{
        [DllImport("user32.dll")]
       public static extern IntPtr GetForegroundWindow();
       [DllImport("user32.dll", CharSet = CharSet.Auto)]
       public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
       [DllImport("user32.dll")]
       static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
       [DllImport("user32.dll")]
       static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO lpgui);
       [StructLayout(LayoutKind.Sequential)]
       public struct GUITHREADINFO
       {
           public int cbSize;
           public int flags;
           public IntPtr hwndActive;
           public IntPtr hwndFocus;
           public IntPtr hwndCapture;
           public IntPtr hwndMenuOwner;
           public IntPtr hwndMoveSize;
           public IntPtr hwndCaret;
           public RECT rectCaret;
       }
 
       [StructLayout(LayoutKind.Sequential)]
       public struct RECT
       {
           int left;
           int top;
           int right;
           int bottom;
       }
       public GUITHREADINFO? GetGuiThreadInfo(IntPtr hwnd)
       {
           if (hwnd != IntPtr.Zero)
           {
               uint threadId = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
               GUITHREADINFO guiThreadInfo = new GUITHREADINFO();
               guiThreadInfo.cbSize = Marshal.SizeOf(guiThreadInfo);
               if (GetGUIThreadInfo(threadId, ref guiThreadInfo) == false)
                   return null;
               return guiThreadInfo;
           }
           return null;
       }
 
       public void SendText(string text)
       {
           IntPtr hwnd = GetForegroundWindow();
           if (String.IsNullOrEmpty(text))
               return;
           GUITHREADINFO? guiInfo = GetGuiThreadInfo(hwnd);
           if (guiInfo != null)
           {
               for (int i = 0; i < text.Length; i++)
               {
                   SendMessage(guiInfo.Value.hwndFocus, 0x0102, (IntPtr)(int)text[i], IntPtr.Zero);
               }
           }
       }
    }
}

调用方式  new SendMsg().SendTest("你要输入的字符串");

 

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早退的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值