473,387 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

C# dll crushed (System.Drawing exception)

The follwing class works well when used in a C# console application:

Expand|Select|Wrap|Line Numbers
  1. namespace ScreenShotDemo
  2. {
  3.     /// <summary>
  4.     /// Provides functions to capture the entire screen, or a particular window, and save it to a file.
  5.     /// </summary>
  6.     public class ScreenCapture
  7.     {
  8.         /// <summary>
  9.         /// Creates an Image object containing a screen shot of the entire desktop
  10.         /// </summary>
  11.         /// <returns></returns>
  12.         public Image CaptureScreen()
  13.         {
  14.             return CaptureWindow(User32.GetDesktopWindow());
  15.         }
  16.         /// <summary>
  17.         /// Creates an Image object containing a screen shot of a specific window
  18.         /// </summary>
  19.         /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
  20.         /// <returns></returns>
  21.         public Image CaptureWindow(IntPtr handle)
  22.         {
  23.             // get te hDC of the target window
  24.             IntPtr hdcSrc = User32.GetWindowDC(handle);
  25.             // get the size
  26.             User32.RECT windowRect = new User32.RECT();
  27.             User32.GetWindowRect(handle, ref windowRect);
  28.             int width = windowRect.right - windowRect.left;
  29.             int height = windowRect.bottom - windowRect.top;
  30.             // create a device context we can copy to
  31.             IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
  32.             // create a bitmap we can copy it to,
  33.             // using GetDeviceCaps to get the width/height
  34.             IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
  35.             // select the bitmap object
  36.             IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
  37.             // bitblt over
  38.             GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
  39.             // restore selection
  40.             GDI32.SelectObject(hdcDest, hOld);
  41.             // clean up 
  42.             GDI32.DeleteDC(hdcDest);
  43.             User32.ReleaseDC(handle, hdcSrc);
  44.             // get a .NET image object for it
  45.             Image img = Image.FromHbitmap(hBitmap);
  46.             // free up the Bitmap object
  47.             GDI32.DeleteObject(hBitmap);
  48.             return img;
  49.         }
  50.         /// <summary>
  51.         /// Captures a screen shot of a specific window, and saves it to a file
  52.         /// </summary>
  53.         /// <param name="handle"></param>
  54.         /// <param name="filename"></param>
  55.         /// <param name="format"></param>
  56.         public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
  57.         {
  58.             Image img = CaptureWindow(handle);
  59.             img.Save(filename, format);
  60.         }
  61.         /// <summary>
  62.         /// Captures a screen shot of the entire desktop, and saves it to a file
  63.         /// </summary>
  64.         /// <param name="filename"></param>
  65.         /// <param name="format"></param>
  66.         public void CaptureScreenToFile(string filename, ImageFormat format)
  67.         {
  68.             Image img = CaptureScreen();
  69.             img.Save(filename, format);
  70.         }
  71.  
  72.         /// <summary>
  73.         /// Helper class containing Gdi32 API functions
  74.         /// </summary>
  75.         private class GDI32
  76.         {
  77.  
  78.             public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
  79.             [DllImport("gdi32.dll")]
  80.             public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
  81.                 int nWidth, int nHeight, IntPtr hObjectSource,
  82.                 int nXSrc, int nYSrc, int dwRop);
  83.             [DllImport("gdi32.dll")]
  84.             public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
  85.                 int nHeight);
  86.             [DllImport("gdi32.dll")]
  87.             public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  88.             [DllImport("gdi32.dll")]
  89.             public static extern bool DeleteDC(IntPtr hDC);
  90.             [DllImport("gdi32.dll")]
  91.             public static extern bool DeleteObject(IntPtr hObject);
  92.             [DllImport("gdi32.dll")]
  93.             public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
  94.         }
  95.  
  96.         /// <summary>
  97.         /// Helper class containing User32 API functions
  98.         /// </summary>
  99.         private class User32
  100.         {
  101.             [StructLayout(LayoutKind.Sequential)]
  102.             public struct RECT
  103.             {
  104.                 public int left;
  105.                 public int top;
  106.                 public int right;
  107.                 public int bottom;
  108.             }
  109.             [DllImport("user32.dll")]
  110.             public static extern IntPtr GetDesktopWindow();
  111.             [DllImport("user32.dll")]
  112.             public static extern IntPtr GetWindowDC(IntPtr hWnd);
  113.             [DllImport("user32.dll")]
  114.             public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
  115.             [DllImport("user32.dll")]
  116.             public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
  117.         }
  118.     }
  119. }
  120.  
  121. But when I use it in a dll for COM object, as in the following:
  122.  
  123. namespace Database_COMObject
  124. {
  125.     [Guid("694C1820-04B6-4988-928F-FD858B95C880")]
  126.     public interface DBCOM_Interface
  127.     {
  128.         [DispId(1)]
  129.         void Init(string userid, string password);
  130.         [DispId(2)]
  131.         bool ExecuteSelectCommand(string selCommand);
  132.         [DispId(3)]
  133.         bool NextRow();
  134.         [DispId(4)]
  135.         void ExecuteNonSelectCommand(string insCommand);
  136.         [DispId(5)]
  137.         string GetColumnData(int pos);
  138.         [DispId(6)]
  139.         string GetMessage(string msg);
  140.         [DispId(7)]
  141.         Image CaptureScreen();
  142.         [DispId(8)]
  143.         Image CaptureWindow(IntPtr handle);
  144.         [DispId(9)]
  145.         Image GetImage(int ms);
  146.     }
  147.  
  148.     // Events interface Database_COMObjectEvents 
  149.     [Guid("47C976E0-C208-4740-AC42-41212D3C34F0"),
  150.     InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
  151.     public interface DBCOM_Events
  152.     {
  153.     }
  154.  
  155.  
  156.     [Guid("9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E"),
  157.     ClassInterface(ClassInterfaceType.None),
  158.     ComSourceInterfaces(typeof(DBCOM_Events))]
  159.     public class DBCOM_Class : DBCOM_Interface
  160.     {
  161.        //-----------------------
  162.         public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
  163.         [DllImport("gdi32.dll")]
  164.         public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
  165.             int nWidth, int nHeight, IntPtr hObjectSource,
  166.             int nXSrc, int nYSrc, int dwRop);
  167.         [DllImport("gdi32.dll")]
  168.         public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
  169.             int nHeight);
  170.         [DllImport("gdi32.dll")]
  171.         public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  172.         [DllImport("gdi32.dll")]
  173.         public static extern bool DeleteDC(IntPtr hDC);
  174.         [DllImport("gdi32.dll")]
  175.         public static extern bool DeleteObject(IntPtr hObject);
  176.         [DllImport("gdi32.dll")]
  177.         public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
  178.         //----------------------
  179.         [StructLayout(LayoutKind.Sequential)]
  180.         public struct RECT
  181.         {
  182.             public int left;
  183.             public int top;
  184.             public int right;
  185.             public int bottom;
  186.         }
  187.         [DllImport("user32.dll")]
  188.         public static extern IntPtr GetDesktopWindow();
  189.         [DllImport("user32.dll")]
  190.         public static extern IntPtr GetWindowDC(IntPtr hWnd);
  191.         [DllImport("user32.dll")]
  192.         public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
  193.         [DllImport("user32.dll")]
  194.         public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
  195.         //----------------------
  196.         private SqlConnection myConnection = null;
  197.         SqlDataReader myReader = null;
  198.  
  199.         public DBCOM_Class()
  200.         {
  201.         }
  202.  
  203.         public void Init(string userid, string password)
  204.         {
  205.             try
  206.             {
  207.                 string myConnectString = "user id=" + userid + ";password=" + password +
  208.                     ";Database=NorthWind;Server=SKYWALKER;Connect Timeout=30";
  209.                 myConnection = new SqlConnection(myConnectString);
  210.                 myConnection.Open();
  211.                 //MessageBox.Show("CONNECTED");
  212.             }
  213.             catch (Exception e)
  214.             {
  215.                 MessageBox.Show(e.Message);
  216.             }
  217.         }
  218.  
  219.         public bool ExecuteSelectCommand(string selCommand)
  220.         {
  221.             if (myReader != null)
  222.                 myReader.Close();
  223.  
  224.             SqlCommand myCommand = new SqlCommand(selCommand);
  225.             myCommand.Connection = myConnection;
  226.             myCommand.ExecuteNonQuery();
  227.             myReader = myCommand.ExecuteReader();
  228.             return true;
  229.         }
  230.  
  231.         public bool NextRow()
  232.         {
  233.             if (!myReader.Read())
  234.             {
  235.                 myReader.Close();
  236.                 return false;
  237.             }
  238.             return true;
  239.         }
  240.  
  241.         public string GetColumnData(int pos)
  242.         {
  243.             Object obj = myReader.GetValue(pos);
  244.             if (obj == null) return "";
  245.             return obj.ToString();
  246.         }
  247.  
  248.         public void ExecuteNonSelectCommand(string insCommand)
  249.         {
  250.             SqlCommand myCommand = new SqlCommand(insCommand, myConnection);
  251.             int retRows = myCommand.ExecuteNonQuery();
  252.         }
  253.  
  254.  
  255.         public string GetMessage(string msg)
  256.         {
  257.             return msg;
  258.         }
  259.         public Image GetImage(int ms)
  260.         {
  261.             return CaptureScreen();
  262.         }
  263.         /// <summary>
  264.         /// Creates an Image object containing a screen shot of the entire desktop
  265.         /// </summary>
  266.         /// <returns></returns>
  267.         public Image CaptureScreen()
  268.         {
  269.             return CaptureWindow(GetDesktopWindow());
  270.         }
  271.         /// <summary>
  272.         /// Creates an Image object containing a screen shot of a specific window
  273.         /// </summary>
  274.         /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
  275.         /// <returns></returns>
  276.         public Image CaptureWindow(IntPtr handle)
  277.         {
  278.             // get te hDC of the target window
  279.             IntPtr hdcSrc = User32.GetWindowDC(handle);
  280.             // get the size
  281.             User32.RECT windowRect = new User32.RECT();
  282.             User32.GetWindowRect(handle, ref windowRect);
  283.             int width = windowRect.right - windowRect.left;
  284.             int height = windowRect.bottom - windowRect.top;
  285.             // create a device context we can copy to
  286.             IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
  287.             // create a bitmap we can copy it to,
  288.             // using GetDeviceCaps to get the width/height
  289.             IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
  290.             // select the bitmap object
  291.             IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
  292.             // bitblt over
  293.             GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
  294.             // restore selection
  295.             GDI32.SelectObject(hdcDest, hOld);
  296.             // clean up 
  297.             GDI32.DeleteDC(hdcDest);
  298.             User32.ReleaseDC(handle, hdcSrc);
  299.             // get a .NET image object for it
  300.             Image img = Image.FromHbitmap(hBitmap);
  301.             // free up the Bitmap object
  302.             GDI32.DeleteObject(hBitmap);
  303.             return img;
  304.         }
  305.     }
  306.  
  307.     /// <summary>
  308.     /// Helper class containing Gdi32 API functions
  309.     /// </summary>
  310.     public class GDI32
  311.     {
  312.  
  313.         public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
  314.         [DllImport("gdi32.dll")]
  315.         public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
  316.             int nWidth, int nHeight, IntPtr hObjectSource,
  317.             int nXSrc, int nYSrc, int dwRop);
  318.         [DllImport("gdi32.dll")]
  319.         public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
  320.             int nHeight);
  321.         [DllImport("gdi32.dll")]
  322.         public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  323.         [DllImport("gdi32.dll")]
  324.         public static extern bool DeleteDC(IntPtr hDC);
  325.         [DllImport("gdi32.dll")]
  326.         public static extern bool DeleteObject(IntPtr hObject);
  327.         [DllImport("gdi32.dll")]
  328.         public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
  329.     }
  330.  
  331.     /// <summary>
  332.     /// Helper class containing User32 API functions
  333.     /// </summary>
  334.     public class User32
  335.     {
  336.         [StructLayout(LayoutKind.Sequential)]
  337.         public struct RECT
  338.         {
  339.             public int left;
  340.             public int top;
  341.             public int right;
  342.             public int bottom;
  343.         }
  344.         [DllImport("user32.dll")]
  345.         public static extern IntPtr GetDesktopWindow();
  346.         [DllImport("user32.dll")]
  347.         public static extern IntPtr GetWindowDC(IntPtr hWnd);
  348.         [DllImport("user32.dll")]
  349.         public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
  350.         [DllImport("user32.dll")]
  351.         public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
  352.     }
  353.     public class Class1
  354.     {
  355.     }
  356. }
  357.  
  358.  
The "GetMessage()" method works well, but the "CaptureScreen()" method will cause "System.Drawing" exception:

NB: I called this from PHP

Fatal error: Uncaught exception 'com_exception' with message '<b>Source:</b> System.Drawing<br/><b>Description:</b> 使用されたパラメータが有効ではありません (The japanese characters mean: The used parameter(s) not valid).

Please do you have any idea?
Thanks in advance
Jul 28 '09 #1
2 3252
tlhintoq
3,525 Expert 2GB
The "*GetMessage()*" method works well, but the "*CaptureScreen()*" method will cause "_System.Drawing_" exception:
Expand|Select|Wrap|Line Numbers
  1. public string GetMessage(string msg)
  2.         {
  3.             return msg;
  4.         }
It would be kind of hard for GetMessage() to NOT work. All it does is return the message sent in. It basically serves no purpose at all since any method calling it already knew the value of 'msg'.

Expand|Select|Wrap|Line Numbers
  1. public Image CaptureWindow(IntPtr handle)
Put a breakpoint on this line. See what value is being passed in when it is called. I'll bet that 'handle' is null.

Since CaptureScreen() is passing out a value it receives from
Expand|Select|Wrap|Line Numbers
  1. [DllImport("user32.dll")]
  2.             public static extern IntPtr GetDesktopWindow();
you are at the mercy of this DLL function. If it fails, then you don't have a value to pass out, so the next method in line fails.

All of your code assumes all the values received will be good. There is no error correction/compensation. If anything comes in that isn't valid it comes crashing down. You need to check that values passed into functions are what you expect and fail gracefully if they aren't.
Jul 29 '09 #2
Plater
7,872 Expert 4TB
I am a bit confused. Your .NET code is almost entirely DLLImports. You are making a .NET DLL that wraps unmanaged DLLImport calls...then wrapping it BACK to an COM DLL...?
Why not just make a plain COM DLL and bypass the .NET overhead for it?
I see you save the image to file but I believe there are methods to do that with hBitmap anyway?
Jul 29 '09 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Terrence | last post by:
I am doing some of the C# walkthroughs to transition from VB to C#. When I try to execute static void Main() { Aplication.Run(new Form1()) } I raise a 'System.NullReferenceException" in...
1
by: gregory_may | last post by:
This code seems to "work" but I get the following errors: An unhandled exception of type 'System.NullReferenceException' occurred in system.windows.forms.dll then this one: An unhandled...
1
by: Rafael | last post by:
Hi, I hope I can find some help for this problem IDE: Visual Studio.NET 2003 Developer Editio Language: C# Problem: "An unhandled exception of type 'System.NullReferenceException' occurred in...
1
by: lwickland | last post by:
Summary: System.Net.ScatterGatherBuffers.MemoryChuck allocates inordinately large bytes when sending large post data. The following application consumes inordinate quantities of memory. My code...
3
by: anastasia | last post by:
I get an out of memory exception when attempting to excecute the following code: original = System.Drawing.Image.FromFile(file.FileName,true); I ONLY get this exception when the file is in the...
2
by: Tyler Foreman | last post by:
Hello, I had an earlier post regarding a strange exception I (thought) I was getting in my windows form. I have since been able to trace the problem to a picturebox control on my form. I can...
1
by: Ratz | last post by:
Hello everyone! I'm new to this Forum! I've spent about 56 hours trying to solve a .NET VB Runtime error while Using a program.Ive contacted the developer of the program and he could not figure out...
3
by: forest demon | last post by:
for example, let's say I do something like, System.Diagnostics.Process.Start("notepad.exe","sample.txt"); if the user does a SaveAs (in notepad), how can i capture the path that the user...
2
by: =?Utf-8?B?TmF0aGFuIFdpZWdtYW4=?= | last post by:
Hi, I am wondering why the .NET Framework is quite different from Win32 API when it comes to displaying system modal message boxes. Consider the four following types of system modal message...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.