c# exe and windows form

本文关键字:form windows and exe | 更新日期: 2023-09-27 17:48:57

我有一个包含文本框的windows窗体应用程序。我想从另一个应用程序(c#应用程序)打开windows窗体exe,并在我的窗体应用程序的文本框中写入。我有以下代码。我在文本框中看不到文本,为什么?

[DllImport("User32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
static void Main(string[] args)
{
    Process myProcess = Process.Start(
        @"C:'WindowsFormsApplication1'bin'Debug'WindowsFormsApplication1.exe");
    SetForegroundWindow(myProcess.Handle);
    if (myProcess.Responding)
    {
        Thread.Sleep(2000);
        System.Windows.Forms.SendKeys.SendWait(
            "This text was entered using the System.Windows.Forms.SendKeys method.");
        System.Windows.Forms.SendKeys.SendWait(" method.");
        //Thread.Sleep(2000);
    }
    else
    {
        myProcess.Kill();
    }

c# exe and windows form

您需要找到要放置文本的正确窗口。你可以通过FindWindowFindWindowEx的组合来实现。之后用该窗口的句柄作为参数调用SetFocus。然后调用SendKeys将文本数据发送到该窗口。

示例代码是这样的:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
static void Main(string[] args)
{
    Process myProcess = Process.Start(@"D:'OtherCode'Test'target'bin'Debug'target.exe");
    SetForegroundWindow(myProcess.Handle);
    IntPtr handleWindow = FindWindow(null, @"Target"); //In place of target, you will pass the caption of your target window
    if (handleWindow != null)
    {
        IntPtr hTextbox = FindWindowEx(handleWindow, IntPtr.Zero, null, null);
        SetFocus(hTextbox);
        Thread.Sleep(2000);
        SendKeys.SendWait("Test");
    }
}

将窗体移动到类库(dll项目)而不是windows应用程序(exe)中,并在新应用程序中引用它。您正在尝试的事情是普通的坏!!!!