Link to home
Start Free TrialLog in
Avatar of Sheldon Livingston
Sheldon LivingstonFlag for United States of America

asked on

c#.NET set focus on a window?

I have written a "sendKeys" app that works well.
I'd like to further its reliability by being able to set focus on expected windows/forms.
The desktop application is written in C#.
So, for example, if the app is ready to supply a username and password to a form who's title bar reads Intuit - Quickbooks Log On, how do I make sure that that window/form has the focus?
Thank you...
Avatar of Dorababu M
Dorababu M
Flag of India image

Are you looking for this?
[DllImport("user32.dll")]
static extern bool SetForegroundWindow (IntPtr hWnd); 
private void BringToFront(Process pTemp)
{    SetForegroundWindow(pTemp.MainWindowHandle); }

Open in new window

Avatar of Sheldon Livingston

ASKER

Dorababu... how do I find the appropriate window handle? For example, I would want the log on window associated with the QuickBooks process.
Can you show some code how you are opening up the quick books thing
Yes...
System.Diagnostics.Process.Start("\"C:\\Program Files (x86)\\Inuit\\QuickBooks 2019\\QBW32.exe\"");
You want the focus back to the form from you are opening?
I want to make sure that I have the log on form has focus before I send the username and password.

I also want to do this periodically to make sure everything is working as planned.

Can you try this as per required
DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

private void button1_Click(object sender, EventArgs e)
{
   Process process = new Process();
   process.StartInfo.FileName = @"D:\LoadTest\WriteLines1.txt";
   process.Start();

   process.WaitForInputIdle();

   SetForegroundWindow(this.Handle);
}

Open in new window

The log on form was just an example... let's say I log in and want to create an account. I push the sendkeys to do that and now I want to make sure  that I am at the "create account" screen before I start sending for keys...
ASKER CERTIFIED SOLUTION
Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@jonathan... although this looks pretty cool I don't see much documentation.
The issue seems to be that sometimes the main program opened loses focus... so I want to set focus back to the main program... particularly the username text box.
The help.chm file shows lots of things in the index, but no pages pop up on the right side.
@Jonathan  I implemented this solution and it appears to be working. Thank you!