简体   繁体   English

C#SetforegroundWindow到VB.Net然后SendKeys

[英]C# SetforegroundWindow to VB.Net then SendKeys

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. 我运行VB.net应用程序,需要输入密码,依次进入“登录”按钮,发送回车,进入“运行负载”按钮并按Enter。 The SendKey part doesn't seem to be the problem; SendKey部分似乎不是问题; it's getting the right application to focus. 它正在寻找合适的应用程序来集中精力。 I was hoping form.TopMost could help, but unfortunately is not the case. 我希望表格可以使用.TopMost可以帮上忙,但不幸的是情况并非如此。

[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. 我尝试了几种不同的方法将VB.net应用程序/进程置于最前面,奇怪的是,有时它可以工作,但有时还不够好。 Does anyone have any ideas? 有人有什么想法吗? I've looked at the first 6 or so google results, too. 我也看过前6个Google搜索结果。 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. 编辑:为澄清起见,此代码启动了VB.net应用程序,而我正在尝试自动执行击键操作以输入凭据,然后按Enter键启动应用程序。 In order for the keystrokes to actually register though, the VB.net application needs to be the Active window. 为了使击键实际注册,VB.net应用程序必须是“活动”窗口。 Also changed my code to be the code that worked (it worked 1/7 tries). 也将我的代码更改为有效的代码(有效1/7次尝试)。

I added Thread.Sleep(2000); 我添加了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. 感谢那些贡献者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM