Graphics.FromHwnd(_pictureBox.Handle)

  • Thread starter Thread starter John Bailo
  • Start date Start date
J

John Bailo

I am walking through some of the very first sample code from the book
"Beginning .NET Game Programming" from Apress. I identify his sample
code with //SC

This code puzzles me:

Graphics graph = new Graphics //SC

// first of all there is no constructor for Graphics
// so in the Form_Paint I use instead:


private void Form1_Paint(object sender, PaintEventArgs pe)
{
Graphics graph = pe.Graphics;



//Then he wants to do:

graph = Graphics.FromHwnd(picSource.Image.); // SC
graph.FillRectangle( // SC
new SolidBrush(Color.Red), // SC
30, 20, 13, 7); // SC


This doesn't work at all because .FromHwnd is expecting an IntPtr

Can some one possibly see what the author is trying to do in this code?

Why would he want to acquire a handle from a pictureBox?

He can get it from:

IntPtr hdc = pe.Graphics.GetHdc();
 
First of all that code has serious typos in. Secondly it's a mess that will
lead you down alleyways you don't want to be walking on a dark night.

I haven't read the book in question. Good job I wasn't the technical
reviewer on that one is all I can say.

You are correct in obtaining the Graphics object from the event arguments in
the Paint handler. You can modify the other mess to draw a rectangle for you
like this:

//Remove the line which reads graph=new Graphics.From.......
//just use...
graph.FillRectangle(Brushes.Red,30,20,13,7);

You'll see a red rectangle on the window.

For more details on how when and where to get the Graphics object, details
of what and what not to do with the picturebox plus a bunch of other stuff
that I'm sure you'll find useful check out the GDI+ FAQ.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Bob said:
First of all that code has serious typos in. Secondly it's a mess that will
lead you down alleyways you don't want to be walking on a dark night.

Thanks for confirming my fears!

This book looks completely /unedited/ right from the start!!!

If I can find the receipt I might return it to Powell's ( $42 bucks !)

I thought Apress was a good publisher, but man, this one is a dog!

I might just read it for the general concepts of gaming math and look
for source on the web....
 
Back
Top