Question

c# drawing to System.Image through hDC

Asked by: dbrckovi

Hi!

I have some dll written in C++, and I'm calling its functions from within C# application.
One of the functions in the dll generates an image, but it expects hDC as parameter.

If I simply pass hDC of the PictureBox, then it will draw the image, but if part of the Picturebox is hidden by other window, it won't draw on that part, and If I minimize the application, the image will dissapear completely.
And besides that, I want to be able to use the generated image somewhere else, and I can't (don't know how to) use it if it gets drawn directly to PictureBox surface.

So now I'm trying to use hDC of the PictureBox.Image, but nothing gets drawn.

I tried looking for the solution but all I could find is when people want to learn how to draw to external hDC, but I need the oposite: to expose hDC of my image so some other application can draw to it.

Do you have any suggestions?
Thanks!

[DllImport("DataMatrixWin32.dll")]
        public static extern void DMRender(long hDC, long x, long y);
 
        private void button1_Click(object sender, EventArgs e)
        {
            //these 2 are not important for my question...
            DataMatrixGenerator.DMSetDefault();
            DataMatrixGenerator.DMSetMessage(DateTime.Now.Ticks.ToString());
 
            Graphics g = pictureBox1.CreateGraphics();        //working
            //Graphics g = Graphics.FromImage(pictureBox1.Image); //not working
            IntPtr hDC = g.GetHdc();
            DataMatrixGenerator.DMRender(hDC.ToInt32(), 0, 0);
            //g.ReleaseHdc();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox1.Image = new Bitmap(pictureBox1.ClientRectangle.Width, pictureBox1.ClientRectangle.Height);
        }

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-06-19 at 14:48:00ID24507195
Tags

C# System.Image hDC ImportDll

Topic

Microsoft Visual C#.Net

Participating Experts
1
Points
70
Comments
6

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Faster Draw/Refresh in PictureBox
    I use a PictureBox control to display a network, i.e. a BIG number of Lines, Circles and Text. Drawing/Refreshing is VERY SLOW. Are there any techniques to accelerate the process? Have heard something about "drawing in memory" but don't know what it is and how it'...
  2. Draw image to PictureBox given hDC
    How do I load an image into a PictureBox only knowing that control's hDC?
  3. Drawing Lines In PictureBox
    may i know what is the code for drawing lines in a picturebox? i need a command button to choose the colour for the line and i also need a command button to delete the lines tt i had draw. thankz
  4. Drawing rectangles on picturebox
    Hi, I counter a problem when I draw a set of rectangles on picturebox, using line method. the rectangles' height are 30 and width are 10, but the result is not what I expect. some rectangles are slim and some are slightly thicker, though they are with same width value. I...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: tcullerPosted on 2009-06-19 at 16:21:48ID: 24670940

You may have to invalidate the PictureBox  after you update the underlying image, because the Control is not aware of its image being tampered with. The method Invalidate forces the control to re-draw itself. To keep the Control constantly up to date, you could subscribe to your picture box' Paint event, and just use the PaintEventArgs.Graphics property to re-draw the image in the method. This will have a performance impact if you do a lot of drawing, however.

There may be something else, but I guess we'll see. Just try calling pictureBox1.Invalidate() at the end of your button1_Click method, and uncomment the line in which you get the Graphics object from the image.

Also, does this method request a 64-bit integer HDC? A long in C++ is not the same as a long in C#; it varies depended on your system, but a long long is usually equivaent to C#'s long (System.Int64, in other words).

If you built the DLL, I would encourage you to enable the passing of 32-bit integers for the x-y coordinates, and a 32-bit HDC (unless you're developing for a 64-bit OS). The coordinates, however, shouldn't ever pass the 2.1~ billion mark, so I don't see a reason to move it up to a long.

Hope that helps, let me know if not,
Nate

 

by: dbrckoviPosted on 2009-06-20 at 07:52:51ID: 24673962

I tried to use PictureBox1.Invalidate() but It's not working.
Even if I use Picturebox.CreateGraphics(), I can see the image flicker for a split second, but then it dissapears.

This method requests 32 bit integer. I had examples written in VB6, so I just automaticaly re-typed 'long' without realising they're not the same in C#.
I have changed it to int now, but there's no difference in application behaviour.

I didn't write this DLL. It's used for generating 2D barcodes and I downloaded it from here:
http://www.brothersoft.com/datamatrix-2d-barcode-win32-dll-download-26239.html

It has few more similar functions, like
 - 'DMSaveAsBMP' but I'd like to avoid having to save the image to disk, just to reopen it in Picturebox.
 - 'DMCopyToClipboard' but it copies it in 'MetafilePict' format which is not directly supported in .NET.

 

by: tcullerPosted on 2009-06-20 at 11:32:30ID: 24674699

Don't create the graphics from your PictureBox; that HDC is different from its Image or BackgroundImage property. Instead, try doing something like the following.

Are you sure the unmanaged method isn't expecting a handle for the HDC, too? Odd things can happen from little mistakes like this (such as the method working on the PictureBox, but not the image ;P)

Hope it helps,
Nate

[DllImport("DataMatrixWin32.dll")]
public static extern void DMRender(Int32 hDC, Int32 x, Int32 y);
 
private Bitmap bmp;
 
private void Form1_Load(object sender, EventArgs e)
{
     this.bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
     pictureBox1.Image = this.bmp;
}
 
private void button1_Click(object sender, EventArgs e)
{
     // Call whatever other methods you need
     Graphics gfx = Graphics.FromImage(this.bmp);
     DataMatrixGenerator.DMRender(gfx.GetHdc().ToInt32(), 0, 0);
     // Screw with bmp using gfx
     pictureBox1.Invalidate();
     // If above didn't work, try using this, too:
     // pictureBox1.Update();
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: dbrckoviPosted on 2009-06-21 at 07:16:18ID: 24677436

Thanks, but it's still not working.

 >> Don't create the graphics from your PictureBox; that HDC is different from its Image or BackgroundImage property.

I know. It is a handle to picturebox'es visible surface. I was using it as an example to show that DLL works on some hDCs and not on others.
This is the reason why I'm asking this question: DLL works on PictureBox hDC, but not in Picturebox1.Image hDC, and since I need this image later (for example to send it to printer, or save it to database), I can't use PictureBox hDC.

>> Are you sure the unmanaged method isn't expecting a handle for the HDC, too?
I'm not sure I understand.
Do you mean some additional parameter?
In example I was copying it from, the function was daclared with these 3 parameters. I've pasted C++ version below:

extern "C" __declspec(dllimport) void _stdcall DMRender(DWORD hDC, WORD x, WORD y);

                                              
1:

Select allOpen in new window

 

by: dbrckoviPosted on 2009-06-21 at 07:39:45ID: 24677494

Hmm.

Something weird is happening.
I created two buttons. Button1 is rendering it to PictureBox hDC and Button2 to PictureBox.Image hDC.

When I press Button1, image appears on the picturebox, then I press Button2 and image dissapears, but If I then drag the form outside desktop and back in very rapidly (10-15 times in 2-3 seconds), eventualy the image will reappear and stay on the Picturebox. I can even get it from PictureBox.Image and use it somewhere else.

Here's the complete code. of my form.
Have you seen anythink like this ever before? :)

        private Bitmap bmp;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            this.bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
            pictureBox1.Image = this.bmp;
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            Graphics gfx = Graphics.FromImage(this.bmp);
            DataMatrixGenerator.DMRender(gfx.GetHdc().ToInt32(), 0, 0);
            pictureBox1.Invalidate();
            pictureBox1.Image = bmp;
            pictureBox1.Update();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            DataMatrixGenerator.DMSetMessage(DateTime.Now.Ticks.ToString());
            DataMatrixGenerator.DMSetSize(pictureBox1.ClientRectangle.Width, pictureBox1.ClientRectangle.Height);
            DataMatrixGenerator.DMSetDefault();
            Graphics gfx = pictureBox1.CreateGraphics();
            DataMatrixGenerator.DMRender(gfx.GetHdc().ToInt32(), 0, 0);
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            //works only after I do that nonsense with rapidly moving form :)
            this.BackgroundImage = pictureBox1.Image;
        }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: dbrckoviPosted on 2009-06-23 at 15:07:51ID: 31594567

The same code is working on all machines except mine. Maybe it's Vista bug or dozens of developer tools I have installed. It doesn't matter as long as it works on customer's computers. So I'm accepting your answer because you gave your best effort to show the correct way to do what I need, and it seems to work on 'normal' machines..

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...