Visual C# 2005 - 如何將 DataGridView 控制項單獨擷取成一個點陣圖檔

摘要:Visual C# 2005 - 如何將 DataGridView 控制項單獨擷取成一個點陣圖檔

圖表1

 

DataGridView 控制項的外觀狀似一個試算表,因此有人希望把 DataGridView 控制項單獨擷取並儲存成一個點陣圖。我們撰寫了一個操作介面如圖表 1 所示的程式,您只需按下表單中的按鈕,即可將表單中的 DataGridView 控制項單獨擷取並儲存成一個點陣圖(.bmp)。 

在此茲將重點程式碼列示如下: 

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);
    }
}