【问题标题】:C# sendkeys not working properly on client sideC# sendkeys 在客户端无法正常工作
【发布时间】:2021-06-06 21:51:36
【问题描述】:

我正在开发 C# WinForms 中的一个工具,用于通过 TCP 共享远程桌面。

到目前为止,我所做的是桌面查看器并将鼠标点击发送到焦点桌面共享窗口。效果很好。

现在,我正在努力将按下的键发送到焦点窗口,但在两种情况下它无法正常工作:

1- 当我按住一个键时

2- 当我开始快速按键时

当我打字慢时,没有问题..

查看器窗口我有这个构造函数:

public ViewerWindow()
{    
        KeyDown += KeyDownHandler;

        InitializeComponent();
 }

这是获取按下的键并写入流以将其传递给客户端的处理程序:

public void KeyDownHandler(object sender, KeyEventArgs e)
{
    var keyPressed = e.KeyData.ToString();
            
    var key = string.Concat("keyboard", " ", keyPressed);
    //sending key here
    byte[] sendBytes = Encoding.UTF8.GetBytes(key);
    client.GetStream().Write(sendBytes, 0, sendBytes.Length);
}

Client 端的 sream 阅读循环中,我有以下代码来接收关键数据并对其进行处理:

if (incomingData.Length > 7 && incomingData.Substring(0, 8) == "keyboard")
{
     string[] inf = incomingData.Split();

     if (inf.Length > 1)
     {
       Keyboard.SendKey(inf[1]);
     }
}

Keyboard 是一个带有 SendKey 方法的静态类,只有以下代码:

public static class Keyboard
{
        [DllImport("User32.dll")]
        static extern int SetForegroundWindow(IntPtr point);

        public static void SendKey(dynamic key)
        {
            SendKeys.SendWait(key);
        }
}

但是,当我按住或快速键入键时,我收到“键盘”字样,似乎 inf[1] 它有“键盘”字样,我不知道为什么......有什么建议/想法来解决它吗?

我是从头开始做的,但不知道这是否是一个不错的解决方案......

任何帮助或指导路径将不胜感激!

谢谢。

【问题讨论】:

    标签: c# .net winforms tcpclient sendkeys


    【解决方案1】:

    可能是您的 TCP 流正在缓冲发送数据,直到它达到更合适的大小?

    写完后试试flushing流。

    byte[] sendBytes = Encoding.UTF8.GetBytes(key);
    var stream = client.GetStream();
    stream.Write(sendBytes, 0, sendBytes.Length);
    stream.Flush();
    

    通常 TCP 连接将多个小数据块收集到一个大 TCP 数据包中以节省网络带宽。通过将TcpClient.NoDelay 属性设置为true 可以覆盖此行为,这将在每次调用Write() 后导致刷新。

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 2018-06-01
      • 2017-09-23
      • 2018-10-12
      • 2018-09-21
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多