Preventing Classes Derived from PrintDocument (and Other Components) from Opening in the Designer by Default





5.00/5 (7 votes)
Does your derived class open in the Visual Studio Designer while having no UI? Annoying, isn't it? This is simple to fix.
Introduction
If you derive a class from Component
, then Visual Studio assumes it's a UI element. Unfortunately, PrintDocument
is derived from Component
- and isn't visual at all, it just uses graphics to draw onto output contexts. But your class counts as a visual element as well despite having no UI, so VS will open it in the design view.
Which promptly brings up a blank screen and invites you to add UI elements to it. :sigh:
To Fix It Is Simple
Just add an attribute to your class definition:
/// <summary>
/// Prints Label sheet.
/// </summary>
/// <remarks>
/// Note the addition of the ComponentModel.DesignerCategory attribute.
/// Without this, the class will always open in the designer by default as
/// PrintDocument derives from Component, which VS believes is a visual element.
/// It isn't - you can't display it if try - but that means it opens in the
/// design view: which promptly complains that you need to add items to it.
/// </remarks>
[System.ComponentModel.DesignerCategory("Code")]
public class MyPrinter : PrintDocument
Now VS will put the icon back to normal, and open in the code view.
History
- 2017-12-23 First version