C# Graphics object - c#

Question: How to check if Graphics object is usable.
My Problem: I create Graphics object from form and give it to "object X" for drawing, when form closes and "object X" tries to draw into Graphics object, GDI+ error occurs 0x80004005.
So i need to check if Graphics is drawable only having that Graphics object.
Any ideas?

The best way to draw objects is that handle the Paint event of the form. in the Paint() will you get access to Graphics which is drawable always. So you can use it without any problems.

When your form is closed you should inform your "object X" of this fact...
Otherwise the only way to know if a Graphics object is accessible is to call a small method on it like GetHdc (with the correct ReleaseHdc after if it succeed) and catch the error that may happens.

Nice idea with GetHdc and ReleaseHdc, VirtualBlackFox, lucks like it worked.
Good job.

Related

saving e.graphics into a pdf problems

i did some e.graphics.draw string/image/line, and i managed to print it using print dialog print document and print previw dialog. but i wanted to save it into a pdf using microsoft print to pdf. into a specific folder. without using the file dialog, just one button to save it as pdf.
i dont have an idea what is the next step. so any help is appreciated, btw i searched for more than 10 days, but i couldn't find a way to do this. btw i used itextsharp,and pdf printer. but i couldn't do what i want because i want to save what i did using e.graphics,thanks in advance.
In order to use the Graphics class for drawing, you have to be able to create an instance for the canvas you want to draw on. Can you do that for a PDF using iTextSharp? I don't know as I've never used it but I don't think I've ever seen it done. I think iTextSharp has its own methods for inserting text, images, etc.
The first thing you need to do is determine whether iTextSharp does/can expose a Graphics instance. If it does not then you can either give up this idea and use the functionality that iTextSharp does provide, or you can use a Graphics object to draw on an Image and then insert that into your PDF using whatever functionality iTextSharp provides for that.
Assuming you're going ahead, the first thing you should do is write a method that takes a Graphics object as an argument and uses it to draw, e.g.
private void Draw(Graphics g)
{
// Call g.DrawString, etc, here.
}
You can then call that method anywhere you have a Graphics object to perform that same drawing. If you are currently using e.Graphics to draw in the PrintPage event handler of a PrintDocument, you would move that code to the method above and change e.Graphics to g, then call the method and pass e.Graphics instead. You can then call the same method elsewhere with different Graphics objects, e.g. create a Bitmap of the desired dimensions, call Graphics.FromImage and then pass the result to that method to do the same drawing on that Bitmap.

How to prevent ExternalException which occurs on graphics object

I'm working on a project where control updates and new image is drawn on a panel after every 10 seconds. Following code clears that panel first. Then draws a border to it.
private void DrawRectangle(Color color)
{
using (var graphics = CreateGraphics())
using (var pen = new Pen(color))
{
graphics.Clear(Color.Black); //External exception is thrown here.
graphics.DrawRectangle(pen, 0, 0, Size.Width - 1, Size.Height - 1);
}
}
Normally everything works fine but if I lock windows(press Win + L) then after 10 seconds when graphics.Clear(Color.Black) statement is executed, application crashes.
According to MSDN page: The Clear method clears the state of the graphics object and should not be called when the graphics object cannot be updated. For example, if the Clear method is called on a secure desktop in a terminal server session, an ExternalException may occur, leaving the Graphics object in an inconsistent state.
What should I do to prevent this crash? Should I check if windows is locked or not? and will that be the only case where this crash will occur?
Update: Same problem occurs when Screen saver is activated.
If you call CreateGraphics() when windows is locked or screensaver is shown, the graphics object it returns is in Inconsistent state and can not be used to paint. If we use such graphics object, it throws ExternalException.
Best way to get rid of this problem is suggested by user Hans Passant. Instead of using CreateGraphics() method to create graphics object, use panel's paint event. Paint event handler contains eventargs which contains graphics object. This graphics object should be used to do painting.
The reason this works because, panel's paint event does not get called when windows is locked or screensaver is shown. So no inconsistent graphics object is used for painting.

The type 'System.Drawing.Graphics' has no constructors defined

Graphics g = new Graphics();
I was trying to create a graphics object for painting on Windows From Application but for some reason, the Graphics() class doesn't have a constructor. How do I create a new object for g. then?
Read the documentation for the class at MSDN
You can obtain a Graphics object by calling the Control.CreateGraphics method on an object that inherits from System.Windows.Forms.Control, or by handling a control's Control.Paint event and accessing the Graphics property of the System.Windows.Forms.PaintEventArgs class. You can also create a Graphics object from an image by using the FromImage method. For more information about creating a Graphics object, see How to: Create Graphics Objects for Drawing.
Continuing from the excellent answer by xbonez...
CreateGraphics() is almost never the correct approach.
If you use the Paint() event, there is a Graphics supplied for you via the arguments usually in the form of e.Graphics.
If you have an Image or Bitmap, you can use Graphics.FromImage() to obtain a Graphics to draw onto the image.
There are examples of these on this page.

How to manually get instance of Graphics object in WinForms?

I know how to work with object of type Graphics (at least I am able to render images) but I always do that by passing graphics object retrieved from OnPaint method.
I would like to display an image when the app is opened (ie in Form_Load method) but have no clue how to obtain the instance of Graphics object I could use?
Thanks
Using the e.Graphics object that OnPaint() supplies to you is the correct way of doing it. It will run right after the OnLoad() method. The form isn't visible yet in OnLoad.
Getting a Graphics object from Control.CreateGraphics() is supported. However, whatever you draw with this will be wiped out as soon as the form repaints itself. Which happens when the user moves another window across yours (pre-Aero) or when she minimizes and restores or otherwise resizes the window. Use CreateGraphics only ever when animating at a high rate.
If you're attempting to create a graphics object from the surface of your form, you can use this.CreateGraphics
If you are attempting to create a new Image, you can always initialize an Image and then call Graphics.CreateGraphics.FromImage(YourImage) e.g.
Bitmap b = new Bitmap(100,100);
var g = Graphics.CreateGraphics.FromImage(b);
At this point, any drawing performed to your Graphics object will be drawn onto your image.
None of the preceding answers worked for me. I found Rajnikant Rajwadi solution effective (see https://social.msdn.microsoft.com/Forums/vstudio/en-US/ce90eb80-3faf-4266-b6e3-0082191793f7/creation-of-graphics-object-in-wpf-user-control?forum=wpf)
Here is a horribly condensed call to Graphics.MeasureString(). (please code more responsibly)
SizeF sf = System.Drawing.Graphics.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle).MeasureString("w", new Font(TheControl.FontFamily.ToString(), (float)TheControl.FontSize));
And how do you plan to use the Graphics object you got in the Load event?
If you want to paint something on the screen, you have to be in the Paint event, or it will be cleared on the next paint.
What you can do: load another (simple) form, with just a picture, and hide it when your main form is loaded.
Since your Load event will probably run on the UI thread. Call DoEvents to make the other form appear.
form.CreateGraphics();
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.creategraphics.aspx
http://msdn.microsoft.com/en-us/library/5y289054.aspx

Printing in C#/.NET, scaling on a whole page

I am wondering how to do the following ( couldn't get google to help me here ):
I got a .jpg file of about 250px*250px in scale..
I want this image on a DIN-A4 page as often as possible
I need an "overlay" for every image on the page with a unique code ( lets say a unique barcode for example )
How would i start here? I have really no idea which classes or methods to use for this...
Also it'd be interesting to know which "formats" i can create the documents in...
Thanks for any help!
Well, you know how big the image is, and how big the paper is, so it's easy to work out how many you can fit on a page.
Then you'll want to create an instance if the Bitmap class from your jpg, then get a Graphics object from the bitmap, call the Graphics object's DrawString method with your text (plus a font, a brush, and a point). Remember to release the Graphics object or, ideally, wrap it in a using statement.Then, as Henk says, use a PrintDocument to print it - there's an example here of that - and write your images in as required to fill the page using the PrintPageEventArgs' Graphics object.

Categories

Resources