将密钥发送到外部应用程序
当尝试将特定密钥发送到另一个应用程序(例如记事本)时,程序员可能会遇到阻止代码无法按预期运行。本文旨在通过探索代码并提供替代解决方案来解决这些挑战。
提供的代码包含以下问题:
要解决这些问题,建议进行以下代码修改:
对于已经运行的记事本:
using System.Diagnostics; ... // Get the first running instance of Notepad Process p = Process.GetProcessesByName("notepad").FirstOrDefault(); if (p != null) { // Get the main window handle IntPtr h = p.MainWindowHandle; SafeNativeMethods.SetForegroundWindow(h); SendKeys.SendWait("k"); }
对于启动记事本并发送密钥:
... // Start Notepad Process p = Process.Start("notepad.exe"); // Wait for the input queue to stabilize p.WaitForInputIdle(); // Get the main window handle IntPtr h = p.MainWindowHandle; SafeNativeMethods.SetForegroundWindow(h); SendKeys.SendWait("k");
通过实施这些更改,代码将首先验证记事本是否正在运行,并且在启动记事本的情况下,将等待应用程序完全运行在发送密钥之前初始化。
非活动窗口注意事项:
虽然不可能直接将密钥发送到后台应用程序,但有一些方法可以将目标应用程序带到前台,然后发送密钥。 SetForegroundWindow 函数允许此功能,如第一个示例中提供的代码所示。
以上是如何可靠地将密钥发送到记事本等外部应用程序?的详细内容。更多信息请关注PHP中文网其他相关文章!