Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Custom Controls » C# scrollable Picturebox custom control

C# scrollable Picturebox custom control

This article discusses the construction of a custom control used to add a scrollable Picturebox control to a project.

Author Rank:
Total page views :  17813
Total downloads :  514
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CCXboxPicCS.zip
 
Become a Sponsor

Introduction:

This article discusses the construction of a custom control used to add a scrollable Picturebox control to a project. There are different ways to scroll an image; it can be done using GDI+ for example, but the approach used in this demo is based upon what I feel is the easiest approach; that being to just scroll a full sized image contained within a panel control set to auto size. By building the control as a custom control, you can reuse in any application where you might need to provide such capability.



Figure 1: Custom Control Loaded into a Test Application

Since the control is based upon the panel control, you will pick up all of the properties contained in the panel control which will make this simple control immediately more useful (for example, you will be able to dock the control into a form).

Getting Started:

In order to get started, unzip the included project and open the solution in the Visual Studio 2008 environment. There are two projects contained in the solution. TestControl is the first project and it is Windows form application used to test the custom control. The second project (XPicbox) is class library containing a single custom control called XtendPicBox.cs.

In the solution explorer, you should note these items:



Figure 2: Solution Explorer

The Custom Control (XtendPicBox.cs)

The extended picture box custom control contains everything necessary to display an image in a scrollable container. The control itself is an extension of the panel control. Within the extended control, a picture box control is configured and added to the panel's control collection. When the control is initialized, the picture box is set to the upper left corner of the control and its size mode is set to normal. Properties within the control are used to both limit the consumer's access to the auto scroll property of the panel control (it has to be set to true in order for the image to scroll) and to allow the consumer to set the image file displayed in the inner picture box at both design and runtime.

The custom control class begins with the following library imports:

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

Following the imports, the namespace and class are defined. A constructor is added as are a collection of local member variables. The local member variables include the declaration of the inner Picturebox control, the path to the Picturebox image, and a Boolean value used to set auto scroll to true (for the extended panel control). The constructor is used to configure the Picturebox and to add the Picturebox control to the extended panel control.

namespace XPicbox
{
    /// <summary>
    /// Extend the panel control to provide a
    /// scrollable picturebox control
    /// </summary>

    public partial class XtendPicBox : Panel
    {

#region Local Member Variables
        PictureBox innerPicture = new PictureBox();
        private string mPictureFile = string.Empty;
        private bool mAutoScroll = true;
        #endregion
#region Constructor 

        /// <summary>

        /// Constructor - set up the inner

        /// picture box so that is plants itself

        /// in the top left corner of the panel

        /// and so that its size mode is always

        /// set to normal.  At normal, the picture

        /// will appear at full size.

        /// </summary>

        public XtendPicBox()

        {

            InitializeComponent();

 

            // add the inner picture

            innerPicture.Top = 0;

            innerPicture.Left = 0;

            innerPicture.SizeMode = PictureBoxSizeMode.Normal;

            Controls.Add(innerPicture);

        }
#endregion

Next up are the custom control's properties. The first property is used to set the image file to be displayed within the inner Picturebox control. Attributes are set to describe the purpose of the property when that property is used within the IDE; the attributes also specify that the property will be set using the file name editor; this will support opening a file browser window within the IDE at design time if the control consumer chooses to set the image file at design time. If the editor were not specified here, the control consumer would have to key in the path the image file.

The second property merely overrides the extended panel control's auto scroll property. By overriding the property and setting up the Browsable attribute to false, the control consumer will be denied the ability to set the property using the property editor at design time. Since we always want the panel's auto scroll property set to true, we block access to the property and set the value within the custom control's code.

#region Properties
 

        /// <summary>

        /// Allow control consumer to set the image

        /// used in the internal picture box through

        /// this public and browsable property -

        /// set the editor to the file name editor

        /// to make the control easier to use at

        /// design time (to provide an interface for

        /// browsing to and selecting the image file

        /// </summary>

        [Category("Image File")]

        [Browsable(true)]

        [Description("Set path to image file.")]

        [Editor(typeof(System.Windows.Forms.Design.FileNameEditor),typeof(System.Drawing.Design.UITypeEditor))]

        public string PictureFile

        {

            get

            {

                return mPictureFile;

            }

            set

            {

                mPictureFile = value;

 

                if (!string.IsNullOrEmpty(mPictureFile))

                {

                    // set the image to the image file

                    innerPicture.Image = Image.FromFile(mPictureFile);

 

                    // resize the image to match the image file

                    innerPicture.Size = innerPicture.Image.Size;

                }

            }

        }

 

        /// <summary>

        /// Override the autoscroll property

        /// and use the browsable attribute

        /// to hide it from control consumer -

        /// The property will always be set

        /// to true so that the picturebox will

        /// always scroll

        /// </summary>

        [Browsable(false)]

        public override bool AutoScroll

        {

            get

            {

                return mAutoScroll;

            }

            set

            {

                mAutoScroll = value;

            }

        }

#endregion

That is all there is to building the custom control. Once compiled, you may use the control in any project where this sort of functionality is needed.

The Test Form (Form1.vb).

Looking at the test project, you will find a single form containing a menu with File --> Open and File --> Exit functions defined and you will find a single instance of the custom control. The custom control is docked full within the form. There is not a lot of code here to worry about; the file open method does demonstrate the ability to set the control's image file at runtime so you might want to take a look at that. The entire body of code for the test form is as follows:

 

using System;

using System.ComponentModel;

using System.Drawing;

using System.Windows.Forms;
 

namespace TestControl

{ 

    /// <summary>

    /// Demo application for scrollable

    /// picturebox control

    /// </summary>

    public partial class Form1 : Form

    { 

        /// <summary>

        /// Default constructor

        /// </summary>

        public Form1()

        {

            InitializeComponent();

        } 

 

        /// <summary>

        /// Open a new image file into the scrollable

        /// picture box control

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void openToolStripMenuItem_Click(object sender, EventArgs e)

        {

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

 

            openFileDialog1.Title = "Open Image File";

            openFileDialog1.Filter = "Bitmap Files|*.bmp" +"|Enhanced Windows MetaFile|*.emf" +"|Exchangeable Image File|*.exif" +"|Gif Files|*.gif|Icons|*.ico|JPEG Files|*.jpg" +"|PNG Files|*.png|TIFF Files|*.tif|Windows MetaFile|*.wmf"; 

            openFileDialog1.FilterIndex = 6;

            openFileDialog1.FileName = "";

            openFileDialog1.ShowDialog();

 

            if (openFileDialog1.FileName == "")

            return; 

            // set the extended picturebox control's

            // image to the open file dialog's filename

            this.xtendPicBox1.PictureFile = openFileDialog1.FileName;

        }
 

        /// <summary>

        /// Close the demo application

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)

        {

            this.Dispose();

        }

    }

}

Summary.

This solution provides a custom control which may be used to display image files in a scrollable container. The methods used within the control are nothing new or novel; the project does provide a simple example of how to construct a custom control, how to extend an existing control, and how to add design time support to a custom control. The same approaches to building this custom control may be applied to constructing other custom controls.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CCXboxPicCS.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
query by ds On December 23, 2008
This is what i'm looking for actually.I also need a scrollable picture box but i'm working on Visual c#.net 2005 window application. how can we use custom picturebox control in vs 2005.any help is appreciated.
Reply | Email | Delete | Modify | 
Re: query by Scott On December 24, 2008
There is nothing unique to VS2008 here; you could just copy the code into a class bearing the same name.
Reply | Email | Delete | Modify | 
how do i read the text from custom control? by balu On February 24, 2009
hi i hope, am writin at a right place. my actual task is to read the long text from the custom control(window) of the third party aplication through my program. any help please.
Reply | Email | Delete | Modify | 
Re: how do i read the text from custom control? by Scott On March 1, 2009
Well this article is about scrollable picture boxes but with regards to your third party control; does the control not expose a text property that you can read from an instance of the control?
Reply | Email | Delete | Modify | 
can we play a video player in this box by Meeta On April 29, 2009
Please can any one tell how should we play a video or .flv player or vlc player in this box.
I need to play a video file only in a minimized size but not for a full screen. Till now i got only full screen code but no small size screen player.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.