473,791 Members | 2,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CreateDC throws error on 203rd loop.

L
Hi guys,

I am writing some interop code to print graphics to an eps file
and I use adobe printer driver. The piece of code I have written is
working fine. but if I loop for more than 200 times, it is throwing an
error. Can anybody tell me why it throws an error or am I having memory
problems? I debuged through it and I see that createDC is returning 0
on 203rd loop and throws an exception. Why is createDC returning a 0?
This is the piece of code that does the interop.

using System;
using System.Drawing;
using System.IO;
using System.Drawing. Printing;
using System.Runtime. InteropServices ;
using System.Drawing. Text;

namespace Printer
{
public class CPrinter
{
private Graphics pDC;
private IntPtr dc1;
private IntPtr hdevmode;

[StructLayout( LayoutKind.Sequ ential)]
public struct DOCINFO
{
[MarshalAs(Unman agedType.LPWStr )]public string pDocName;
[MarshalAs(Unman agedType.LPWStr )]public string pOutputFile;
[MarshalAs(Unman agedType.LPWStr )]public string pDataType;
}

[DllImport(
"winspool.drv", CharSet=CharSet .Unicode,ExactS pelling=false,
CallingConventi on=CallingConve ntion.StdCall )]
public static extern long StartDocPrinter (IntPtr hPrinter, int Level,
ref DOCINFO pDocInfo);

[DllImport("gdi3 2.dll", EntryPoint="Cre ateDCA")]
public static extern IntPtr CreateDC(string lpDriverName, string
lpDeviceName,
string lpOutput, IntPtr pDevMode);

[DllImport("gdi3 2.dll")]
static extern bool DeleteDC(IntPtr hdc);

[DllImport("gdi3 2", EntryPoint="Sta rtDocA")]
public static extern int StartDoc(IntPtr dc1, ref DOCINFO di);

[DllImport("gdi3 2")] public static extern int StartPage(IntPt r hDC);
[DllImport("gdi3 2")] public static extern int EndDoc(IntPtr hDC);

[DllImport("gdi3 2")] public static extern int EndPage(IntPtr hDC);

public CPrinter()
{
}
public void StartPrinter(st ring outputFile)
{
try
{
DOCINFO di = new DOCINFO();
di.pOutputFile = outputFile;
PrintDocument pd = new PrintDocument() ;
hdevmode = pd.PrinterSetti ngs.GetHdevmode ();
dc1 = CreateDC("","Ac robat Distiller 3x2",outputFile ,hdevmode);
int result = StartDoc(dc1, ref di);
result = StartPage(dc1);
pDC = Graphics.FromHd c(dc1);
pDC.PageUnit = GraphicsUnit.Pi xel;
}
catch(Exception ex)
{
throw(ex);
}
}

public void EndPrinter()
{
int result = EndPage(dc1);
result = EndDoc(dc1);
DeleteDC(dc1);
}
}
}

This is the piece of code where I loop :

using System;
using Printer;

namespace ConsoleApplicat ion1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int i = 0;
try
{
while (true)
{
CPrinter AdobePrinter = new CPrinter();
AdobePrinter.St artPrinter("tem p.wrk");
AdobePrinter.En dPrinter();
i++;
Console.WriteLi ne(i);
}
}
catch (Exception ex)
{
Console.WriteLi ne( i + " : " + ex);
}
}
}
}

Thanks,
Lalasa.

Nov 16 '05 #1
9 4978
"L" <la********@inv estors.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Hi guys,

I am writing some interop code to print graphics to an eps file
and I use adobe printer driver. The piece of code I have written is
working fine. but if I loop for more than 200 times, it is throwing an
error. Can anybody tell me why it throws an error or am I having memory
problems? I debuged through it and I see that createDC is returning 0
on 203rd loop and throws an exception. Why is createDC returning a 0?

You are using a Disposable object (Graphics) without disposing it.


This is the piece of code that does the interop.

using System;
using System.Drawing;
using System.IO;
using System.Drawing. Printing;
using System.Runtime. InteropServices ;
using System.Drawing. Text;

namespace Printer
{
public class CPrinter
{
private Graphics pDC;
private IntPtr dc1;
private IntPtr hdevmode;

[StructLayout( LayoutKind.Sequ ential)]
public struct DOCINFO
{
[MarshalAs(Unman agedType.LPWStr )]public string pDocName;
[MarshalAs(Unman agedType.LPWStr )]public string pOutputFile;
[MarshalAs(Unman agedType.LPWStr )]public string pDataType;
}

[DllImport(
"winspool.drv", CharSet=CharSet .Unicode,ExactS pelling=false,
CallingConventi on=CallingConve ntion.StdCall )]
public static extern long StartDocPrinter (IntPtr hPrinter, int Level,
ref DOCINFO pDocInfo);

[DllImport("gdi3 2.dll", EntryPoint="Cre ateDCA")]
public static extern IntPtr CreateDC(string lpDriverName, string
lpDeviceName,
string lpOutput, IntPtr pDevMode);

[DllImport("gdi3 2.dll")]
static extern bool DeleteDC(IntPtr hdc);

[DllImport("gdi3 2", EntryPoint="Sta rtDocA")]
public static extern int StartDoc(IntPtr dc1, ref DOCINFO di);

[DllImport("gdi3 2")] public static extern int StartPage(IntPt r hDC);
[DllImport("gdi3 2")] public static extern int EndDoc(IntPtr hDC);

[DllImport("gdi3 2")] public static extern int EndPage(IntPtr hDC);

public CPrinter()
{
}
public void StartPrinter(st ring outputFile)
{
try
{
DOCINFO di = new DOCINFO();
di.pOutputFile = outputFile;
PrintDocument pd = new PrintDocument() ;
hdevmode = pd.PrinterSetti ngs.GetHdevmode ();
dc1 = CreateDC("","Ac robat Distiller 3x2",outputFile ,hdevmode);
int result = StartDoc(dc1, ref di);
result = StartPage(dc1);
pDC = Graphics.FromHd c(dc1);
pDC.PageUnit = GraphicsUnit.Pi xel;
}
catch(Exception ex)
{
throw(ex);
}
}

public void EndPrinter()
{
int result = EndPage(dc1);
result = EndDoc(dc1);
DeleteDC(dc1);
}
}
}

This is the piece of code where I loop :

using System;
using Printer;

namespace ConsoleApplicat ion1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int i = 0;
try
{
while (true)
{
CPrinter AdobePrinter = new CPrinter();
AdobePrinter.St artPrinter("tem p.wrk");
AdobePrinter.En dPrinter();
i++;
Console.WriteLi ne(i);
}
}
catch (Exception ex)
{
Console.WriteLi ne( i + " : " + ex);
}
}
}
}

Thanks,
Lalasa.

Nov 16 '05 #2
L

I added the pDC.Dispose() to my EndPrinter() function and still I am
having the problem.

public void EndPrinter()
{
int result = EndPage(dc1);
result = EndDoc(dc1);
pDC.Dispose();
DeleteDC(dc1);
}

Thanks,
L.

Nov 16 '05 #3
Can anybody tell me why it throws an error or am I having memory
problems?
You're net freeing the handle returned by GetHDevmode.

public static extern long StartDocPrinter (IntPtr hPrinter, int Level,

^^^^

The return type should be (u)int.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #4
L
Can you tell me the method I should use to release the handle returned
by GetHDevmode? I am not able to find one.

Thanks,
Lalasa.

Nov 16 '05 #5
Can you tell me the method I should use to release the handle returned
by GetHDevmode?


The GlobalFree Win32 API, just like thie documentation says.

http://msdn.microsoft.com/library/en...modeTopic1.asp

Marshal.FreeHGl obal probably works as well.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #6
L
Thankyou very much for helping out.

Nov 16 '05 #7
L
Hi,

Is there anything else I got to correct. Because I am having the
same error now after 1122 loops.
Here is my EndPrinter() function

public void EndPrinter()
{
int result = EndPage(dc1);
result = EndDoc(dc1);
pDC.Dispose();
Marshal.FreeHGl obal(hdevmode); // Frees the memory. You could also
free the memory by calling the native win32 globalfree method.
DeleteDC(dc1);
}

Thanks in advance
Lalasa.

Mattias Sjögren wrote:
Can you tell me the method I should use to release the handle returnedby GetHDevmode?
The GlobalFree Win32 API, just like thie documentation says.

http://msdn.microsoft.com/library/en...modeTopic1.asp
Marshal.FreeHGl obal probably works as well.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.


Nov 16 '05 #8
Is there anything else I got to correct. Because I am having the
same error now after 1122 loops.


Well your DOCINFO struct doesn't look correct compared to the one in
the MSDN documentation.

Then I recommend that you use Task Manager to monitor the number of
GDI handles used in your application to ensure that you're not leaking
any.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #9
L
Well, I figured it out. The memory leak was happening in my main code
where I was using interop calls for creating fonts. I fixed my dispose
function to delete all the fonts and it is working in an end less loop
now. Thanks for the help.

Lalasa.

Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
3228
by: jerrygarciuh | last post by:
Hi all, I was just wondering what popular opinion is on PHP giving this warning: Warning: Invalid argument supplied for foreach() in /home/boogerpic/public_html/my.php on line 6 when presented with an indefined variable. It makes sense to me to warn if an unacceptably defined var is passed but it
0
1686
by: Piotr Bieniek | last post by:
Hello, I have a problem with UDP sockets. It concerns UdpClient class as well. It throws strange exceptions on subsequent Send calls. Exception is SocketException with native error code 10049. I noticed that it happens when I call Send for the second time in my program. It seemed strange, so I compiled and run Chat sample program from MSDN. To my surprise, it worked. But then I modified it. The only change was that I duplicated sending...
2
5217
by: Piotr Bieniek | last post by:
Hello, I have a problem with UDP sockets. It concerns UdpClient class as well. It throws strange exceptions on subsequent Send calls. Exception is SocketException with native error code 10049. I noticed that it happens when I call Send for the second time in my program. It seemed strange, so I compiled and run Chat sample program from MSDN. To my surprise, it worked. But then I modified it. The only change was that I duplicated sending...
1
1875
by: Mike C# | last post by:
Hi all, I'm writing a little app that uses ODBC to call a SQL 2K stored procedure several times in a loop, with a different parameter each time. The SP can return no results in some instances. When no results are returned, the CRecordset throws an exception. I've tracked the problem down to dbcore.cpp, where the CRecordset::Open method performs a MoveNext() after executing the SP (it apparently doesn't bother checking that any results...
1
2120
by: Me | last post by:
Hello, The code below runs well on IE 6 and 7. On Firefox it loads the first time but throws the following error on reloads. Error: top is not defined Source File: top.myIFrameBody(); Line: 1
5
5602
by: kyosohma | last post by:
Hi, I am trying to create a post logon script which does various tasks, like setup a printer based on location. While most of it works very fast, I have a second Python script that I run that scans the PC using WMI (among other things) and writes the following to a database: Name, Username, Machine, IP, Login Date,CPU,Memory. The problem I have is that since I import WMI, it takes a long time and we have users complaining about it. So...
2
5388
by: sbasavar | last post by:
Hi All, In my excel programming, I am using XML http object (MSXML2.XMLHTTP.3.0). Using this object when I try to send a request application throws an "Access is Denied" error. Strange thing here is that the request absolutely works fine on some systems with Excel 2003 and doesn't throw any error; but same patch of code throws an error with Excel 2000, 2002, 2007 and even on some of 2003 systems. Following is sample of code I am...
4
2279
by: wordone | last post by:
Sometimes it works, sometimes it doesn't but I can't find the bug: package Loop.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TheLoopTest {
2
2897
by: alireza6485 | last post by:
Hi, Could you please rewrite the program for me?I tried my best and the program still does not do what it has to do. I have to write a code that generates random speed and distance .it ask the user for angle and start calculating the vertical and horizantal positions. when the vertical position gets negative program should stop and check the horizantal position and print out different messeges based on the value of the horizantal speed. ...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9993
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5558
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4109
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3713
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.