By default in Cefsharp, the print dialog is enabled so websites can interact with it using
window.print. You can as well print the current content of the window by simply right-clicking and selecting Print from the dropdown menu. There are multiple reasons why you wouldn't like to allow such a feature in your project. Many apps that use chromium don't allow such a feature of course just as Discord, Slack, or others.
In this article, I will explain to you the basics to block printing in your WinForms project based on Cefsharp.
1. Disable or customize Cefsharp context menu
As you may know, when launching a simple instance of Cefsharp, the context menu is enabled by default and allows the user to print the page:
You may want to remove this from the context menu as well. We wrote previously 2 different articles about how to remove or customize the context menu of Cefsharp:
- How to prevent the native Context Menu from appearing on a CefSharp control in WinForms
- How to customize new items to the native Context Menu on a CefSharp control in WinForms
According to your needs, you may opt-in for one or another.
2. Override window.print
window.print, it will still work of course. To remove this possibility, you need to overwrite the
window.print with an empty function that shouldn't damage any code, the method won't just work as usual and that's it, the logic should be the following one during the initialization:
The following code applies the mentioned logic in a single initialization of Cefsharp in a single form so you can implement it as well in your own project:
Happy coding ❤️!
Become a more social person