C# :: Aufgabe #208
1 Lösung
Screenshots erstellen und abspeichern
Anfänger - C#
von Exception
- 17.05.2018 um 15:36 Uhr
Aufgaben:
1) Erstelle ein Windows Forms Programm, welches via Buttonklick einen Screenshot erstellen kann.
2) Zusätzlich soll dieser Screenshot dann in einem beliebigen Ordner abgespeichert werden können, aber nur, falls dies der Nutzer auch möchte.
3) Das Bild kann dann dementsprechend in verschiedenen Formaten abgespeichert werden (png, jpg, …)
Optional:
- Gib dem Nutzer zusätzlich die Möglichkeit nur einen gewissen Bereich des Bildschirms als Screenshot abspeichern zu können (man möchte ja ggf. nur ein Fenster o.ä. aufnehmen)
- Möglichkeit das Bild um x Grad drehen
- Möglichkeit etwas in das Bild zeichnen, z.B. einen roten Rahmen
- Farbverläufe?
- etc. etc. etc.
Was ist ein Screenshot? Klicke hier!
1) Erstelle ein Windows Forms Programm, welches via Buttonklick einen Screenshot erstellen kann.
2) Zusätzlich soll dieser Screenshot dann in einem beliebigen Ordner abgespeichert werden können, aber nur, falls dies der Nutzer auch möchte.
3) Das Bild kann dann dementsprechend in verschiedenen Formaten abgespeichert werden (png, jpg, …)
Optional:
- Gib dem Nutzer zusätzlich die Möglichkeit nur einen gewissen Bereich des Bildschirms als Screenshot abspeichern zu können (man möchte ja ggf. nur ein Fenster o.ä. aufnehmen)
- Möglichkeit das Bild um x Grad drehen
- Möglichkeit etwas in das Bild zeichnen, z.B. einen roten Rahmen
- Farbverläufe?
- etc. etc. etc.
Was ist ein Screenshot? Klicke hier!
Lösungen:
Der Form Designer
Die Form Klasse
C#-Code
namespace Screenshot { partial class Form1 { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.screenshotBox = new System.Windows.Forms.PictureBox(); this.screenshotBtn = new System.Windows.Forms.Button(); this.selectionTim = new System.Windows.Forms.Timer(this.components); this.selectionBtn = new System.Windows.Forms.Button(); this.saveImageBtn = new System.Windows.Forms.Button(); this.imageSaveFileDlg = new System.Windows.Forms.SaveFileDialog(); this.imageRotateTb = new System.Windows.Forms.TrackBar(); this.label1 = new System.Windows.Forms.Label(); this.rotateImageBtn = new System.Windows.Forms.Button(); this.gradTbox = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.screenshotBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imageRotateTb)).BeginInit(); this.SuspendLayout(); // // screenshotBox // this.screenshotBox.Location = new System.Drawing.Point(12, 12); this.screenshotBox.Name = "screenshotBox"; this.screenshotBox.Size = new System.Drawing.Size(753, 343); this.screenshotBox.TabIndex = 0; this.screenshotBox.TabStop = false; // // screenshotBtn // this.screenshotBtn.Location = new System.Drawing.Point(12, 370); this.screenshotBtn.Name = "screenshotBtn"; this.screenshotBtn.Size = new System.Drawing.Size(93, 23); this.screenshotBtn.TabIndex = 1; this.screenshotBtn.Text = "Make Screen!"; this.screenshotBtn.UseVisualStyleBackColor = true; this.screenshotBtn.Click += new System.EventHandler(this.screenshotBtn_Click); // // selectionTim // this.selectionTim.Enabled = true; this.selectionTim.Interval = 1; this.selectionTim.Tick += new System.EventHandler(this.selectionTim_Tick); // // selectionBtn // this.selectionBtn.Location = new System.Drawing.Point(12, 399); this.selectionBtn.Name = "selectionBtn"; this.selectionBtn.Size = new System.Drawing.Size(183, 29); this.selectionBtn.TabIndex = 2; this.selectionBtn.Text = "Make Screen With Selection"; this.selectionBtn.UseVisualStyleBackColor = true; this.selectionBtn.Click += new System.EventHandler(this.selectionBtn_Click); // // saveImageBtn // this.saveImageBtn.Location = new System.Drawing.Point(12, 434); this.saveImageBtn.Name = "saveImageBtn"; this.saveImageBtn.Size = new System.Drawing.Size(75, 23); this.saveImageBtn.TabIndex = 3; this.saveImageBtn.Text = "Save Image"; this.saveImageBtn.UseVisualStyleBackColor = true; this.saveImageBtn.Click += new System.EventHandler(this.saveImageBtn_Click); // // imageRotateTb // this.imageRotateTb.Location = new System.Drawing.Point(12, 488); this.imageRotateTb.Maximum = 360; this.imageRotateTb.Minimum = 1; this.imageRotateTb.Name = "imageRotateTb"; this.imageRotateTb.Size = new System.Drawing.Size(753, 45); this.imageRotateTb.TabIndex = 4; this.imageRotateTb.Value = 1; this.imageRotateTb.Scroll += new System.EventHandler(this.imageRotateTb_Scroll); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 472); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(71, 13); this.label1.TabIndex = 5; this.label1.Text = "Rotate Image"; // // rotateImageBtn // this.rotateImageBtn.Location = new System.Drawing.Point(121, 519); this.rotateImageBtn.Name = "rotateImageBtn"; this.rotateImageBtn.Size = new System.Drawing.Size(75, 23); this.rotateImageBtn.TabIndex = 7; this.rotateImageBtn.Text = "Rotate Image"; this.rotateImageBtn.UseVisualStyleBackColor = true; this.rotateImageBtn.Click += new System.EventHandler(this.rotateImageBtn_Click); // // gradTbox // this.gradTbox.Location = new System.Drawing.Point(15, 522); this.gradTbox.Name = "gradTbox"; this.gradTbox.Size = new System.Drawing.Size(100, 20); this.gradTbox.TabIndex = 8; this.gradTbox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.gradTbox_KeyPress); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(777, 580); this.Controls.Add(this.gradTbox); this.Controls.Add(this.rotateImageBtn); this.Controls.Add(this.label1); this.Controls.Add(this.imageRotateTb); this.Controls.Add(this.saveImageBtn); this.Controls.Add(this.selectionBtn); this.Controls.Add(this.screenshotBtn); this.Controls.Add(this.screenshotBox); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.screenshotBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imageRotateTb)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox screenshotBox; private System.Windows.Forms.Button screenshotBtn; private System.Windows.Forms.Timer selectionTim; private System.Windows.Forms.Button selectionBtn; private System.Windows.Forms.Button saveImageBtn; private System.Windows.Forms.SaveFileDialog imageSaveFileDlg; private System.Windows.Forms.TrackBar imageRotateTb; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button rotateImageBtn; private System.Windows.Forms.TextBox gradTbox; } }
Die Form Klasse
C#-Code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace Screenshot { public partial class Form1 : Form { Image currentImage; public Form1() { InitializeComponent(); } Form selectionForm; private void Form1_Load(object sender, EventArgs e) { screenshotBox.SizeMode = PictureBoxSizeMode.StretchImage; InitSelectionForm(); } private void InitSelectionForm() { selectionForm = new Form(); selectionForm.BackColor = Color.Black; selectionForm.TransparencyKey = Color.Black; selectionForm.FormBorderStyle = FormBorderStyle.None; selectionForm.Bounds = Screen.PrimaryScreen.Bounds; selectionForm.TopMost = true; } #region NativeStuff [Flags] private enum KeyStates { None = 0, Down = 1, Toggled = 2 } [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } private const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter [DllImport("user32.dll")] private static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] private static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,int nHeight); [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] private static extern bool DeleteDC(IntPtr hDC); [DllImport("User32.dll")] public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc); [DllImport("gdi32.dll")] private static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.dll")] private static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,int nWidth, int nHeight, IntPtr hObjectSource,int nXSrc, int nYSrc, int dwRop); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] private static extern short GetKeyState(int keyCode); private static KeyStates GetKeyState(Keys key) { KeyStates state = KeyStates.None; short retVal = GetKeyState((int)key); //If the high-order bit is 1, the key is down //otherwise, it is up. if ((retVal & 0x8000) == 0x8000) state |= KeyStates.Down; //If the low-order bit is 1, the key is toggled. if ((retVal & 1) == 1) state |= KeyStates.Toggled; return state; } private static Image CaptureScreen() { return CaptureSelection(GetDesktopWindow()); } private static Image CaptureSelection(IntPtr handle) { // get te hDC of the target window IntPtr hdcSrc = GetWindowDC(handle); // get the size RECT windowRect = new RECT(); GetWindowRect(handle, ref windowRect); int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; // create a device context we can copy to IntPtr hdcDest = CreateCompatibleDC(hdcSrc); // create a bitmap we can copy it to, // using GetDeviceCaps to get the width/height IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height); // select the bitmap object IntPtr hOld = SelectObject(hdcDest, hBitmap); // bitblt over BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY); // restore selection SelectObject(hdcDest, hOld); // clean up DeleteDC(hdcDest); ReleaseDC(handle, hdcSrc); // get a .NET image object for it Image img = Image.FromHbitmap(hBitmap); // free up the Bitmap object DeleteObject(hBitmap); return img; } private static Image CropImage(Image img, Rectangle cropRect) { Image returnImage = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(returnImage)) { g.DrawImage(img, new Rectangle(0, 0, returnImage.Width, returnImage.Height), cropRect, GraphicsUnit.Pixel); } return returnImage; } private static bool IsKeyDown(Keys key) { return KeyStates.Down == (GetKeyState(key) & KeyStates.Down); } private static Image RotateImage(Image img, float rotationAngle) { //create an empty Bitmap image Bitmap bmp = new Bitmap(img.Width, img.Height); //turn the Bitmap into a Graphics object Graphics gfx = Graphics.FromImage(bmp); //now we set the rotation point to the center of our image gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2); //now rotate the image gfx.RotateTransform(rotationAngle); gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2); //set the InterpolationMode to HighQualityBicubic so to ensure a high //quality image once it is transformed to the specified size gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; //now draw our new image onto the graphics object gfx.DrawImage(img, new Point(0, 0)); //dispose of our Graphics object gfx.Dispose(); //return the image return bmp; } #endregion private bool inSelection = false; private bool inSelectionSetting = false; PictureBox selectionBox = new PictureBox(); private void DrawOnDesktop() { InitSelectionForm(); selectionBox.BorderStyle = BorderStyle.FixedSingle; selectionBox.SetBounds(0, 0, 0, 0); selectionForm.Controls.Add(selectionBox); selectionForm.ShowDialog(); } private void screenshotBtn_Click(object sender, EventArgs e) { currentImage = CaptureScreen(); screenshotBox.Image = currentImage; } private void selectionTim_Tick(object sender, EventArgs e) { if (inSelection) { if (IsKeyDown(Keys.LButton)) { selectionBox.Location = Cursor.Position; inSelection = false; inSelectionSetting = true; } } if (inSelectionSetting) { if(Cursor.Position.X > selectionBox.Location.X) selectionBox.Width = Cursor.Position.X- selectionBox.Location.X; else selectionBox.Width = selectionBox.Location.X - Cursor.Position.X; if (Cursor.Position.Y > selectionBox.Location.Y) selectionBox.Height = Cursor.Position.Y - selectionBox.Location.Y; else selectionBox.Height = selectionBox.Location.Y - Cursor.Position.Y; if (!IsKeyDown(Keys.LButton)) { inSelectionSetting = false; selectionBox.BorderStyle = BorderStyle.None; currentImage = CropImage(CaptureScreen(),new Rectangle(selectionBox.Location.X, selectionBox.Location.Y, selectionBox.Width, selectionBox.Height)); screenshotBox.Image = currentImage; selectionForm.Close(); selectionForm = null; } } selectionBox.Refresh(); } private void selectionBtn_Click(object sender, EventArgs e) { inSelection = true; DrawOnDesktop(); } private void saveImageBtn_Click(object sender, EventArgs e) { imageSaveFileDlg.Filter = "JPeg Image|*.jpg|PNG Image|*.png|Bitmap Image|*.bmp|Gif Image|*.gif"; imageSaveFileDlg.Title = "Save an Image File"; imageSaveFileDlg.ShowDialog(); if (imageSaveFileDlg.FileName != "" && currentImage != null) { // Saves the Image via a FileStream created by the OpenFile method. System.IO.FileStream fs = (System.IO.FileStream)imageSaveFileDlg.OpenFile(); // Saves the Image in the appropriate ImageFormat based upon the // File type selected in the dialog box. // NOTE that the FilterIndex property is one-based. switch (imageSaveFileDlg.FilterIndex) { case 1: currentImage.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); break; case 2: currentImage.Save(fs, System.Drawing.Imaging.ImageFormat.Png); break; case 3: currentImage.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp); break; case 4: currentImage.Save(fs, System.Drawing.Imaging.ImageFormat.Gif); break; } fs.Close(); } } private void imageRotateTb_Scroll(object sender, EventArgs e) { gradTbox.Text = imageRotateTb.Value.ToString(); } private void rotateImageBtn_Click(object sender, EventArgs e) { if (currentImage != null) { currentImage = RotateImage(currentImage, float.Parse(gradTbox.Text)); screenshotBox.Image = currentImage; } } private void gradTbox_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // only allow one decimal point if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } } }