0

Is there any way to run code in my asp.net c# web application if the print hotkey (ctrl+P) is pressed by the user?

I have an multiline asp:TextBox and I need to calculate the number of rows to generate the correct height of the textbox for the document. Atm I have an Print- Button, which works really fine, but I want to run the same code if the browser print function is used by the user.

Thank you in advance

raven_977
  • 475
  • 2
  • 8
  • 25
  • why not use Javascript to calculate the rows, instead? Then you don't need a request to the server. – ADyson Oct 01 '20 at 08:09
  • That would be possible too but I prefer the solution with server request because I can do some additional stuff in one step. Thank you anyway, I appreciate your help. – raven_977 Oct 02 '20 at 07:33

1 Answers1

2

I would do something like this in Webforms. Make a dummy Button or LinkButton and trigger the click on that with jQuery when Control+P is pressed. Then in code behind write window.print() to the page with the ScriptManager.

The <span> element in the LinkButton is needed to register the click.

<script>
    $(window).bind('keydown', function (e) {
        if ((e.ctrlKey || e.metaKey) && String.fromCharCode(e.which).toUpperCase() === 'P') {
            $('#LinkButton1')[0].click(); 
            e.preventDefault();
        }
    });
</script>

<asp:LinkButton ID="LinkButton1" runat="server" 
    ClientIDMode="Static" OnClick="LinkButton1_Click"><span></span></asp:LinkButton>

And then the code

protected void LinkButton1_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "PrintWindow", "window.print()", true);
}
VDWWD
  • 35,079
  • 22
  • 62
  • 79