C#:System.Windows.Forms.SendKeys.SendWait 不适用于路径作为输入

C#: System.Windows.Forms.SendKeys.SendWait does not work with the path as input

这是我的代码

private string path = Path.GetTempPath() + "Test.pdf";
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
System.Windows.Forms.SendKeys.SendWait(path);
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
Keyboard.SendKeys("{Enter}");

有一个用于打开文件的 window 资源管理器。该文件存在于临时路径中。它有时会起作用,有时它会以 :\Users\.... 的形式输入路径,这意味着它会忽略 C。我不确定是什么问题?为什么不一致?感谢任何帮助。

我已经试过了

private string path = @"" + Path.GetTempPath() + "Test.pdf";

但它是一样的(有时有效,有时无效)

我在路径前添加了空字符

private string path = @" " + Path.GetTempPath() + "Test.pdf";

但还是一样!

尝试使用

Path.Combine(Path.GetTempPath(), "Test.pdf")

我对 Coded UI 也有类似的问题,但它在整个字符串中随机省略了少量字符。我从来没有找出真正的原因,但我通过一次发送一个字符并在它们之间稍作停顿来解决这个问题。我使用类似于以下的代码:

void SendKeysSlowly(string text)
{
    foreach ( char s in text )
    {
        SendKeys(s); // Choose the appropriate send routine
        System.Threading.Thread.Sleep(50); // Milliseconds, adjust as needed
    }
}

此外,您应该确保字符串始终以 "C:" 开头?您可以在第一个 ...Sendkeys 调用之前添加 Assert(path.StartsWith("C:\")); 形式的代码。