Home > front end >  Control P not working using selenium C#
Control P not working using selenium C#

Time:11-09

I am trying to print the web page and save as pdf using selenium C#. But Ctrl P key is not working. I tried all the below possible methods

1 - SendKeys.SendWait(Keys.Control "P");

2 -

Actions vaction = new Actions(driver);
            vaction.KeyDown(Keys.Control);
            vaction.SendKeys("p");
            vaction.KeyUp(Keys.Control);
            vaction.Build().Perform();

3 - using javascript print dialog is appearing but after that enter key is not working to save the page as pdf

((IJavaScriptExecutor)driver).ExecuteScript("window.print()");
        driver.SwitchTo().Window(driver.WindowHandles.Last());
        SendKeys.SendWait("{ENTER}");

CodePudding user response:

The normal sendkeys syntax would be

1)

SendKeys.SendWait("^p"); // or ("^{p}")

where ^ is the symbol for Control hence {^} is literal ^

normally applied with a wait because the enter would be premature

    SendKeys.SendWait("^p");
    // give it time to render the print
    System.Threading.Thread.Sleep(5000);
    SendKeys.SendWait("~");

    // give it time to spool onto the printer
    System.Threading.Thread.Sleep(5000);
  1. longhand
keysEventInput.Click();

            Actions vAction = new Actions(driver);
            IAction pressControl = vAction.KeyDown(keysEventInput, Keys.Control).Build();
            pressControl.Perform();

            IAction sendLowercase = vAction.SendKeys(keysEventInput, "p").Build();
            sendLowercase.Perform();

            IAction releaseControl = vAction.KeyUp(keysEventInput, Keys.Control).Build();
            releaseControl.Perform();

So try those, but unsure why

  1. is not working other than its not focused where needed its easier if its a findelement button on page to button.click() or element.sendKeys(Keys.ENTER);

perhaps https://github.com/MicrosoftEdge/WebView2Feedback/issues/1471#issuecomment-871315418 helps

also consider

// press Enter programmatically - the print dialog must have focus, obviously
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
  • Related