5

I am writing a method that will take a screenshot of a passed form element, and print it out. There are a few challenges I am facing. I want to be able to make this method generic enough to accept just about any type of form element. I set the "element" argument to type "object". I think I will also need to pass a "type" argument or is there a way to figure out what type the object is after it is passed?

static public void PrintFormElement(object element, ?type?){

}

Am I approaching this problem the right way? Any advice would be appreciated thanks!

sooprise
  • 22,657
  • 67
  • 188
  • 276

4 Answers4

4

You can find out what type something is either using the is/as operators, or using GetType. It's usually a bit of a design smell if you have to use them though. What are you planning to do that's type-specific?

If you're talking about visual elements, you might want to use Control instead of object.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

I guess that your element should be Control, and every Control has DrawToBitmap() method that you can use to take 'screenshot' of it.

So you can forget all about type parameter, because you won't need it, because of polymorphism.

Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
  • Hey, that's pretty good. Now I'm kind of curious, this is working fine except for one thing. When I try to print a richTextBox, if there is text inside of the box, it doesn't actually print. Is there any way around this? – sooprise Feb 11 '11 at 21:28
1

I think object is too generic, I'd go for Control instead. You don't need to pass in the type though, you can just query it for it's type using is.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
1

To expand on the answers suggesting to use the Control base class. I'd make your function an extension method to avoid creating ASDFHelper, ASDFUtility and other classes full of static methods.

static public void PrintFormElement(this Control element){
    element.DrawToBitmap();
}

This can then be invoked like this

new TextBox().PrintFormElement();
Novikov
  • 4,399
  • 3
  • 28
  • 36