C# SetforegroundWindow to VB.Net then SendKeys

958 views Asked by At

I'm automating some processes. I run a VB.net application and need to input a password, tab through to the "sign in" button, send enter, tab through to the "run loads" button and hit enter. The SendKey part doesn't seem to be the problem; it's getting the right application to focus. I was hoping form.TopMost could help, but unfortunately is not the case.

[DllImport("User32")]
        private static extern int SetForegroundWindow(int hwnd);
        public void runDailyWS()
        {
            string homeWSPath = "D:\\...";

            var home = Process.Start(homeWSPath);

            var procName = "DataLoad Home Test - Copy";
        Process[] p = Process.GetProcessesByName(procName);

        // Activate the first application we find with this name
        if (p.Count() > 0)
            {
                SetForegroundWindow(p[0].MainWindowHandle);
                SendKeys.SendWait("{TAB}");
                SendKeys.SendWait("password");
                SendKeys.SendWait("{TAB}");
                SendKeys.SendWait("{TAB}");
                SendKeys.SendWait("{TAB}");
                SendKeys.SendWait("{ENTER}");
            }
///Did not post rest of code after this point as it's unnecessary

I've tried a few different ways to bring the VB.net application/process to the front and the strange thing is that it works sometimes, but sometimes isn't good enough. Does anyone have any ideas? I've looked at the first 6 or so google results, too. Thanks.

EDIT: To clarify, this code starts a VB.net application and I'm trying to automate keystrokes to enter credentials and start the application by hitting enter. In order for the keystrokes to actually register though, the VB.net application needs to be the Active window. Also changed my code to be the code that worked (it worked 1/7 tries).

1

There are 1 answers

0
HanH1113 On

I added Thread.Sleep(2000); because the code was just inputting the keystrokes before the application even had a chance to fully load. I don't know if this solution will help anyone else, but it's definitely something to consider. Thanks to those who contributed.