下面的代码示例设计用于 Windows 窗体,它需要 PaintEventArgse(这是 Paint 事件处理程序的参数)。该示例演示如何调用 Windows GDI 函数以执行与 GDI+Graphics 方法相同的任务。代码执行下列操作: 为 Windows DLL 文件 gdi32.dll 定义互操作性 DllImportAttribute 属性。此 DLL 包含所需的 GDI 函数。将该 DLL 中的 Rectangle 函数定义为外部函数。创建一支红色钢笔。利用该钢笔,使用 GDI+DrawRectangle 方法将矩形绘制到屏幕。定义内部指针类型变量 hdc 并将它的值设置为窗体的设备上下文句柄。使用 GDIRectangle 函数将矩形绘制到屏幕。释放由 hdc 参数表示的设备上下文。
public class GDI
{
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    internal static extern bool Rectangle(
       IntPtr hdc,
       int ulCornerX, int ulCornerY,
       int lrCornerX, int lrCornerY);
}[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand, Flags = 
System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)]            
public void GetHdcForGDI1(PaintEventArgs e)
{    //实例化pen.
    Pen redPen = new Pen(Color.Red, 1);    // 用GDI+绘制矩形.
    e.Graphics.DrawRectangle(redPen, 10, 10, 100, 50);    //获取上下文handle.
    IntPtr hdc = e.Graphics.GetHdc();    //用自定义GDI绘制矩形.
    GDI.Rectangle(hdc, 10, 70, 110, 120);    //释放上下文handle.
    e.Graphics.ReleaseHdc(hdc);
}

解决方案 »

  1.   

    Graphics   g   =   g.FromImage(bmp); 
    这样创建的Graphics应该不还有hdc吧。
      

  2.   

    [DllImport("gdi32.dll", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)]
    public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);
    参数中的各种DC可以用Graphics.GetHdcGraphics gSave=Graphics.FromImage(bmp);     
    HandleRef hDcSave=new HandleRef(null,gSave.GetHdc());    //得到句柄