Visual C# 2005 - 如何将 DataGridView 控件单独截取成一个位图文件

 

DataGridView 控件的外观状似一个电子表格,因此有人希望把 DataGridView 控件单独截取并储存成一个位图。我们撰写了一个操作接口如图表 1 所示的程序,您只需按下窗体中的按钮,即可将窗体中的 DataGridView 控件单独截取并储存成一个位图(.bmp 

表1

 

在此兹将重点程序代码列示如下: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Data.SqlClient;


[DllImport("gdi32.dll", CharSet=CharSet.Auto)]
 
private static extern bool  BitBlt(
     IntPtr pHdc, int iX,
    
int iY, int nWidth,
    
int nHeight, IntPtr pSrcDC,
    
int xSrc, int ySrc,
    
Int32 dwRop            
   
 );        

 
private const int SRC = 0xCC0020;

 
private DataSet myDataSet;

public void ConvertDataGridViewToBMP(DataGridView e, string myBitmapFilePath)
{
  
 e.Refresh();
   
e.Select();

   
Graphics g = e.CreateGraphics();

   
Bitmap ibitMap = new Bitmap(e.ClientSize.Width, e.ClientSize.Height, g);
   
Graphics iBitMap_gr = Graphics.FromImage(ibitMap);
   
IntPtr iBitMap_hdc = iBitMap_gr.GetHdc();
   
IntPtr me_hdc = g.GetHdc();

  
 BitBlt(iBitMap_hdc, 0, 0, e.ClientSize.Width,
         
 e.ClientSize.Height, me_hdc, 0, 0, SRC);
 
  g.ReleaseHdc(me_hdc);
    iBitMap_gr.ReleaseHdc(iBitMap_hdc);

   
if (myBitmapFilePath == "")
  
 {
       
return;
  
 }

  
 ibitMap.Save(myBitmapFilePath, ImageFormat.Bmp);
}

private void Button1_Click(object sender, EventArgs e)
{
   
try
    {
        SaveFileDialog1.Title = "
储存成位图";
        SaveFileDialog1.Filter = "
位图档 (*.bmp)|*.bmp";

       
if(SaveFileDialog1.ShowDialog() ==
                   System.Windows.Forms.DialogResult.Cancel)
      
 {
           
return;
     
  }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
  
 }

   
string myBitmapFilePath;

  
 myBitmapFilePath = SaveFileDialog1.FileName;

   
if (myBitmapFilePath == "")
    {
        return;
 
  }
    else
    {
        this.ConvertDataGridViewToBMP(DataGridView1, myBitmapFilePath);
    }
}

章立民研究室敬上

期待更多精彩,敬请关注:

http://www.china-pub.com/static/jsj_zlm_060824.html

 

 

posted on 2006-10-12 09:37  章立民研究室  阅读(4328)  评论(9编辑  收藏  举报

导航