Reputation: 743
I have a windows form application that contains a textbox. I want to open the windows form exe from another application (c# application) and write in the textbox from my form application. I have the following code. I don't see the text in my textbox .Why?
[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();
}
Upvotes: 0
Views: 1600
Reputation: 15546
You need to find the correct window in which you want to place the text. You can do this through FindWindow
and FindWindowEx
combination. After that call SetFocus
with the handle of that window as parameter. And only after that call SendKeys
to send text data to that window.
Sample code would be something like this:
[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");
}
}
Upvotes: 1
Reputation: 3844
Move the form to a class library (dll project) instead an windows application (exe), and reference this in your new application. The thing you are trying is plain BAD!!!!
Upvotes: 1