I have a WinForms WebView2 project that is a simple bot running some JavaScript on a webpage. I am using JS to click an element on the webpage and download a file. The website prompts me with "Are you sure you want to leave the page?" dialog, So I want to send the RETURN keyboard press to confirm that I want to leave the webpage and download the file.
I want to run this automatically using windows Task Scheduler. This method works, as long as I am remote connected to my server and the window is not minimized. However, when I am not remote connected to my server, my enter keypress returns and error.
I have tried this code with SendKeys
//Get Webview proccess
Process p = Process.GetProcessesByName("msedgewebview2").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
printToTextbox("pressed ENTER key");
SendKeys.SendWait("{ENTER}");
await checkDownloadFinished();
}
I start my Bot and then exit my remote session. When I return, this error is given when the program reaches SendKeys.SendWait("{ENTER}");
System.ComponentModel.Win32Exception: 'Access is denied'
I also tried the Nuget package InputSimulator
Process p = Process.GetProcessesByName("msedgewebview2").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
printToTextbox("pressed ENTER key");
InputSimulator s = new InputSimulator();
s.Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
await checkDownloadFinished();
}
Following the same proccess, I start my bot and exit my remote session. When I return, I am met with this error:
System.Exception: 'Some simulated input commands were not sent successfully. The most common reason
for this happening are the security features of Windows including User Interface Privacy Isolation
(UIPI). Your application can only send commands to applications of the same or lower elevation.
Similarly certain commands are restricted to Accessibility/UIAutomation applications. Refer to the
project home page and the code samples for more information.'
Is there another c# compatible way to send keystrokes? Or is there a way to prevent the dialog from ever popping up? Thank you!
You're doing it wrong :-)
You should try to look at: CoreWebView2.ScriptDialogOpening Event.
The scriptdialogopening
has its eventargs with an Accept()
method to click Ok
on the dialog.
Here's the eventargs link: CoreWebView2ScriptDialogOpeningEventArgs
Now you don't have to mess with SendKeys
.