Windows Forms: How to use a Custom control in C#
By FoxLearn 7/25/2017 8:27:27 PM 5.02K
Create custom picture box with scrollbars in C# using custom control.
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "CustomControl" and then click OK
Step 2: Design your form as below
Step 3: Create a custom control, then modify your code as below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CustomControl { public partial class MyPictureBox : Panel { PictureBox pictureBox; public MyPictureBox() { InitializeComponent(); pictureBox = new PictureBox(); this.Controls.Add(pictureBox); } [Category("Custom")] [Browsable(true)] [Description("Set path to image file")] [Editor(typeof(System.Windows.Forms.Design.WindowsFormsComponentEditor),typeof(System.Drawing.Design.UITypeEditor))] public string ImageFile { set { //Set image to picture box Image img = Image.FromFile(value); pictureBox.Image = img; pictureBox.Size = img.Size; } } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); } } }
Step 4: Add code to handle your form
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CustomControl { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnOpen_Click(object sender, EventArgs e) { using(OpenFileDialog ofd=new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "JPEG|*.jpg" }) { if (ofd.ShowDialog() == DialogResult.OK) { txtFileName.Text = ofd.FileName; myPictureBox1.ImageFile = ofd.FileName; } } } } }
VIDEO TUTORIALS
Categories
Popular Posts
How to Download Chromedriver for Selenium
08/29/2024
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024