C# 如何在完全加载(或空闲)时启动另一个程序并与其文本框交互

C# 如何在完全加载(或空闲)时启动另一个程序并与其文本框交互,c#,winforms,C#,Winforms,我想启动一个包含文本框的查找程序(.exe)。我想从主窗体启动此程序,并将粘贴数据从主窗体复制到查找程序(.exe)中 我已经编写了一些代码来实现这一点,它工作得很好,但我使用Thread.Sleep()来等待程序加载。我在考虑像WaitForInputIdle()这样的东西,但我不确定它是如何工作的 私有IntPtr句柄; 私有void启动程序() { //将数据字段中的文本复制到剪贴板 Clipboard.SetText(serialTextBox.Text,TextDataFormat.T

我想启动一个包含文本框的查找程序(.exe)。我想从主窗体启动此程序,并将粘贴数据从主窗体复制到查找程序(.exe)中

我已经编写了一些代码来实现这一点,它工作得很好,但我使用Thread.Sleep()来等待程序加载。我在考虑像WaitForInputIdle()这样的东西,但我不确定它是如何工作的

私有IntPtr句柄;
私有void启动程序()
{
//将数据字段中的文本复制到剪贴板
Clipboard.SetText(serialTextBox.Text,TextDataFormat.Text);
bool isRunning=Process.getProcessByName(“Serial Search.exe”).Any();
使用(流程=新流程())
{
如果(!正在运行)
{                       
process.StartInfo.FileName=@“C:\Serial Search.exe”;
process.Start();
//给进程一些时间启动-我想删除这一行,并在完全加载时进行交互
《睡眠》(2000年);
Process[]pname=Process.GetProcessesByName(“Serial Search.exe”);
如果(pname.Length>0)
{
handle=pname[0]。MainWindowHandle;
SetForegroundWindow(手柄);
}
var activatedHandle=GetForegroundWindow();
var vPprocess=Process.GetProcessesByName(“Serial Search.exe”);
而(GetActiveWindowTitle()=“串行搜索”)
{
SendKeys.Send(“^V”);
SendKeys.Send(“{ENTER}”);
打破
}
}
其他的
{
Process[]pname=Process.GetProcessesByName(“Serial Search.exe”);
handle=pname[0]。MainWindowHandle;
SetForegroundWindow(手柄);
var activatedHandle=GetForegroundWindow();
var vPprocess=Process.GetProcessesByName(“Serial Search.exe”);
而(GetActiveWindowTitle()=“串行搜索”)
{
SendKeys.Send(“^A”);
SendKeys.Send(“^V”);
SendKeys.Send(“{ENTER}”);
打破
}
}
}
}
}

我想删除Thread.Sleep部分,让表单在加载时立即与.exe交互。你知道我该怎么做吗?

也许可以走这条混乱的路线,检查特定像素的颜色,这将表明程序已加载。或者查找与加载程序相关联的进程的CPU使用率下降或硬盘驱动器使用率下降

您可以将代码简化为:

private IntPtr handle;
private void launchProgram()
{
    handle = IntPtr.Zero;
    string fullPathFileName = @"C:\Serial Search.exe";
    string friendlyFileName = System.IO.Path.GetFileNameWithoutExtension(fullPathFileName);
    Process P = Process.GetProcessesByName(friendlyFileName).FirstOrDefault();
    if (P != null)
    {
        handle = P.MainWindowHandle;
    }
    else
    {
        P = Process.Start(fullPathFileName);
        P.WaitForInputIdle();
        handle = P.MainWindowHandle;
    }

    if (!handle.Equals(IntPtr.Zero))
    {
        // Copy the text in the datafield to Clipboard
        Clipboard.SetText(serialTextBox.Text, TextDataFormat.Text);
        handle = pname[0].MainWindowHandle;
        SetForegroundWindow(handle);
        SendKeys.Send("^A");
        SendKeys.Send("^V");
        SendKeys.Send("{ENTER}");
    }
}
请注意,希望文件名的“友好”版本结尾没有“.exe”:

进程名称是进程的友好名称,例如Outlook, 不包括.exe扩展名或路径