C# 保存窗體爲圖片(保存縱斷面圖)

源碼以下:函數

     #region 保存縱斷面截圖

        private void button_save_Click(object sender , EventArgs e)
        {
            SaveFileDialog saveImageDialog = new SaveFileDialog();
            saveImageDialog.Title = "保存縱斷面圖";
            saveImageDialog.DefaultExt = ".png";
            saveImageDialog.FileName = Linefeaturelayer.Name + "縱斷面圖";
            saveImageDialog.InitialDirectory = "C:\\";

            DialogResult dr = saveImageDialog.ShowDialog();
            if (dr==DialogResult.OK)
            {
                CaptureImage(saveImageDialog.FileName);
                MessageBox.Show("保存成功!");
            }

        }

        private void CaptureImage(string path)
        {
            try
            {
                //得到當前屏幕的大小
                Rectangle rect = new Rectangle();
                rect = Screen.GetWorkingArea(this);
                //建立一個以當前屏幕爲模板的圖象
                Graphics g1 = this.CreateGraphics();
                //建立以屏幕大小爲標準的位圖 
                Image MyImage = new Bitmap(rect.Width , rect.Height , g1);
                Graphics g2 = Graphics.FromImage(MyImage);
                //獲得屏幕的DC
                IntPtr dc1 = g1.GetHdc();
                //獲得Bitmap的DC 
                IntPtr dc2 = g2.GetHdc();
                //調用此API函數,實現屏幕捕獲
                BitBlt(dc2 , 0 , 0 , rect.Width , rect.Height , dc1 , 0 , 0 , 13369376);
                //釋放掉屏幕的DC
                g1.ReleaseHdc(dc1);
                //釋放掉Bitmap的DC 
                g2.ReleaseHdc(dc2);
                //以JPG文件格式來保存
                MyImage.Save(path , ImageFormat.Png);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message + " 保存圖片失敗!"); 
            }
        }

        //聲明一個API函數
        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
     
        private static extern bool BitBlt(
            
            IntPtr hdcDest , // 目標 DC的句柄
            int nXDest ,
            int nYDest ,
            int nWidth ,
            int nHeight ,
            IntPtr hdcSrc ,  // 源DC的句柄
            int nXSrc ,
            int nYSrc ,
            System.Int32 dwRop  // 光柵的處理數值
            
            );

        #endregion
效果圖:

相關文章
相關標籤/搜索