visual styles independent drawing

蹲街弑〆低调 提交于 2020-01-03 17:27:54

问题


Using C# winforms, i want to create custom controls that looks like the real ones.

There are a lot of classes that can be used to draw controls that looks like the real ones: ControlPaint, VisualStyleRenderer, ButtonRenderer, CheckBoxRenderer, ComboBoxRenderer, GroupBoxRenderer, ProgressBarRenderer, RadioButtonRenderer, ScrollBarRenderer, TabRenderer, TextBoxRenderer, TextRenderer, ToolStripProfessionalRenderer, ToolStripRenderer, ToolStripSystemRenderer, TrackBarRenderer.

The problems coming when considering visual styles: I want to be visual styles independent. Meaning: I dont care if user allowing visual-styles or not, i want it to work. if user enabled visual-styles, i want to draw it using visual-styles, otherwise i want to draw it without visual-styles.

By the MSDN documentation, the only classes that are visual-styles independent are ButtonRenderer, CheckBoxRenderer, GroupBoxRenderer, RadioButtonRenderer. That means that for all other cases i need to check myself if visual-styles enabled and use different code to draw the parts.

Suppose i want to draw a Tab control parts myself. TabRenderer class has all needed functionality for that, but it works only if user enabled visual styles. otherwise I need to use ControlPaint class to draw, but it uses completely different model, there is no ControlPaint.DrawTab() method or something like that, and i need to figure out what rectangle types i need to draw so it will look like a real tab. that`s annoying.

The built-in controls, including the Tab control, already have this functionality of drawing themselves with or without visual styles. Why doesn`t microsoft exposing this functionality for the custom control creators? Why are custom control creators should suffer?


回答1:


It's a pain unfortunately, but that is the cost for writing custom controls. The way I have seen Microsoft do this in many of the WinForm controls, is to check Application.RenderWithVisualStyes, and Control.UseVisualStyleBackColor. Depending on those values they will paint the control accordingly.

A common pattern they use is to create internal classes called MyControlRenderer.cs. Inside this renderer is where the magic actually happens. If you look at the NET REF code, you will see that they also use VisualStyleRenderer class from System.Windows.Forms.VisualStyles namespace, and there is some actual paint code as well.

You will need to utilize a mix of these various classes and tools, and a mix of also doing your own work. Testing your control on a machine with, and without visual styles.

When I hope home from work I will post a bit more.



来源:https://stackoverflow.com/questions/3484143/visual-styles-independent-drawing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!