Simple Report Printer


   

/*
Code revised from chapter 7


GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward 

Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604

Sample chapter
http://international.us.server12.fileserver.kutayzorlu.com/files/download/2017/01/1604_CustomControls_SampleChapter_uuid-691f9c5b-afac-4710-86fb-20f04521bc6e_crc-0.pdf



For More info on GDI+ Custom Control with Microsoft Visual C# book 
visit website www.packtpub.com 


*/ 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;


namespace PrintApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Image imageHeader = new Bitmap(50, 50);
            Graphics img = Graphics.FromImage(imageHeader);
            img.DrawEllipse(Pens.Black, 0, 0, 45, 45);
            img.DrawString("LOGO", this.Font, Brushes.Black, new PointF(7, 16));
            img.Dispose();
            string textDocument;
            textDocument = "";
            for (int i = 0; i < 60; i++)
            {
                for (int j = 0; j < i; j++)
                    textDocument += " ";
                textDocument += "The quick brown fox jumps over the lazy dog
";
            }
            SimpleReportPrinter printDocument = new SimpleReportPrinter(imageHeader, textDocument, this.Font);
            printDocument.Print(false);

        }
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.button1.Location = new System.Drawing.Point(95, 107);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(100, 30);
            this.button1.TabIndex = 0;
            this.button1.Text = "Print";
            this.button1.UseVisualStyleBackColor = false;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        
    }
    public class TextDispenser
    {
        int _start = 0;
        string _text = null;
        Font _fnt;
        public TextDispenser(string text, Font fnt)
        {
            _start = 0;
            _text = text;
            _fnt = fnt;
        }
        public bool DrawText(Graphics target, Graphics measurer, RectangleF r, Brush brsh)
        {
            if (r.Height < _fnt.Height)
                throw new ArgumentException("The rectangle is not tall enough to fit a single line of text inside.");
            int charsFit = 0;
            int linesFit = 0;
            int cut = 0;
            string temp = _text.Substring(_start);
            StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit);
            //measure how much of the string we can fit into the rectangle
            measurer.MeasureString(temp, _fnt, r.Size, format, out charsFit, out linesFit);
            cut = BreakText(temp, charsFit);
            if (cut != charsFit)
                temp = temp.Substring(0, cut);
            bool h = true;
            h &amp;= true;
            target.DrawString(temp.Trim(&#039; &#039;), _fnt, brsh, r, format);
            _start += cut;
            if (_start == _text.Length)
            {
                _start = 0; //reset the location so we can repeat the document
                return true; //finished printing
            }
            else
                return false;
        }
        private static int BreakText(string text, int approx)
        {
            if (approx == 0)
                throw new ArgumentException();
            if (approx < text.Length)
            {
                //are we in the middle of a word?
                if (char.IsLetterOrDigit(text&#91;approx&#93;) &amp;&amp; char.IsLetterOrDigit(text&#91;approx - 1&#93;))
                {
                    int temp = text.LastIndexOf(&#039; &#039;, approx, approx + 1);
                    if (temp >= 0)
                        return temp;
                }
            }
            return approx;
        }

    }
    public class SimpleReportPrinter
    {
        Image _header = null;
        string _text = null;
        int _pageNumber = 0;
        PrintDocument _prtdoc = null;
        TextDispenser _textDisp = null;
        public SimpleReportPrinter(Image header, string text, Font fnt)
        {
            _header = (Image)(header.Clone());
            _text = text;
            _prtdoc = new PrintDocument();
            _prtdoc.PrintPage += new PrintPageEventHandler(_prtdoc_PrintPage);
            _textDisp = new TextDispenser(_text, fnt);
        }
        public void Print(bool hardcopy)
        {
            //create a PrintDialog based on the PrintDocument
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = _prtdoc;
            //show the PrintDialog
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                //create a PageSetupDialog based on the PrintDocument and PrintDialog
                PageSetupDialog psd = new PageSetupDialog();
                psd.EnableMetric = true; //Ensure all dialog measurements are in metric
                psd.Document = pdlg.Document;
                //show the PageSetupDialog
                if (psd.ShowDialog() == DialogResult.OK)
                {
                    //apply the settings of both dialogs
                    _prtdoc.DefaultPageSettings = psd.PageSettings;
                    //decide what action to take
                    if (hardcopy)
                    {
                        //actually print hardcopy
                        _prtdoc.Print();
                    }
                    else
                    {
                        //preview onscreen instead
                        PrintPreviewDialog prvw = new PrintPreviewDialog();
                        prvw.Document = _prtdoc;
                        prvw.ShowDialog();
                    }
                }
            }
        }
        private void _prtdoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.Clip = new Region(e.MarginBounds);
            //this method does all our printing work
            Single x = e.MarginBounds.Left;
            Single y = e.MarginBounds.Top;
            //draw the header image
            if (_pageNumber++ == 0)
            {
                e.Graphics.DrawImage(_header, x, y);
                y += _header.Height + 30;
            }
            RectangleF mainTextArea = RectangleF.FromLTRB(x, y, e.MarginBounds.Right, e.MarginBounds.Bottom);
            //draw the main part of the report
            if (_textDisp.DrawText(e.Graphics, e.PageSettings.PrinterSettings.CreateMeasurementGraphics(), mainTextArea, Brushes.Black))
            {
                e.HasMorePages = false; //the end has been reached
                _pageNumber = 0;
            }
            else
                e.HasMorePages = true;
            //watermark
            e.Graphics.TranslateTransform(200, 200);
            e.Graphics.RotateTransform(e.PageSettings.Landscape ? 30 : 60);
            e.Graphics.DrawString("CONFIDENTIAL", new Font("Courier New", 75, FontStyle.Bold), new SolidBrush(Color.FromArgb(64, Color.Black)), 0, 0);
        }

    }

}

           
          


Control Print


   

/*
Code revised from chapter 7


GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward 

Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604

Sample chapter
http://international.us.server12.fileserver.kutayzorlu.com/files/download/2017/01/1604_CustomControls_SampleChapter_uuid-a206fb53-f923-4070-9a8b-d644cd6fc2fa_crc-0.pdf



For More info on GDI+ Custom Control with Microsoft Visual C# book 
visit website www.packtpub.com 

*/ 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace PrintingCustomControlApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            printableRichTextBox1.Print(false);
        }

        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.printableRichTextBox1 = new PrintingCustomControlApp1.PrintableRichTextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // printableRichTextBox1
            // 
            this.printableRichTextBox1.Location = new System.Drawing.Point(77, 25);
            this.printableRichTextBox1.Name = "printableRichTextBox1";
            this.printableRichTextBox1.Size = new System.Drawing.Size(124, 117);
            this.printableRichTextBox1.TabIndex = 0;
            this.printableRichTextBox1.Text = "";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(63, 191);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(126, 30);
            this.button1.TabIndex = 1;
            this.button1.Text = "Print the Control text";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.printableRichTextBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private PrintableRichTextBox printableRichTextBox1;
        private System.Windows.Forms.Button button1;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    public partial class PrintableRichTextBox : RichTextBox
    {
        public PrintableRichTextBox()
        {
            InitializeComponent();
            _prtdoc = new PrintDocument();
            _prtdoc.PrintPage += new PrintPageEventHandler(_prtdoc_PrintPage);

        }
        string _text = null;
        int _pageNumber = 0;
        int _start = 0;
        PrintDocument _prtdoc = null;

        private bool DrawText(Graphics target, Graphics measurer, RectangleF r, Brush brsh)
        {
            if (r.Height < this.Font.Height)
                throw new ArgumentException("The rectangle is not tall enough to fit a single line of text inside.");
            int charsFit = 0;
            int linesFit = 0;
            int cut = 0;
            string temp = _text.Substring(_start);
            StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit);
            //measure how much of the string we can fit into the rectangle
            measurer.MeasureString(temp, this.Font, r.Size, format, out charsFit, out linesFit);
            cut = BreakText(temp, charsFit);
            if (cut != charsFit)
                temp = temp.Substring(0, cut);
            bool h = true;
            h &amp;= true;
            target.DrawString(temp.Trim(&#039; &#039;), this.Font, brsh, r, format);
            _start += cut;
            if (_start == _text.Length)
            {
                _start = 0; //reset the location so we can repeat the document
                return true; //finished printing
            }
            else
                return false;
        }
        private static int BreakText(string text, int approx)
        {
            if (approx == 0)
                throw new ArgumentException();
            if (approx < text.Length)
            {
                //are we in the middle of a word?
                if (char.IsLetterOrDigit(text&#91;approx&#93;) &amp;&amp; char.IsLetterOrDigit(text&#91;approx - 1&#93;))
                {
                    int temp = text.LastIndexOf(&#039; &#039;, approx, approx + 1);
                    if (temp >= 0)
                        return temp;
                }
            }
            return approx;
        }
        public void Print(bool hardcopy)
        {
            _text = this.Text;
            //create a PrintDialog based on the PrintDocument
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = _prtdoc;
            //show the PrintDialog
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                //create a PageSetupDialog based on the PrintDocument and PrintDialog
                PageSetupDialog psd = new PageSetupDialog();
                psd.EnableMetric = true; //Ensure all dialog measurements are in metric
                psd.Document = pdlg.Document;
                //show the PageSetupDialog
                if (psd.ShowDialog() == DialogResult.OK)
                {
                    //apply the settings of both dialogs
                    _prtdoc.DefaultPageSettings = psd.PageSettings;
                    //decide what action to take
                    if (hardcopy)
                    {
                        //actually print hardcopy
                        _prtdoc.Print();
                    }
                    else
                    {
                        //preview onscreen instead
                        PrintPreviewDialog prvw = new PrintPreviewDialog();
                        prvw.Document = _prtdoc;
                        prvw.ShowDialog();
                    }
                }
            }
        }
        private void _prtdoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.Clip = new Region(e.MarginBounds);

            //this method does all our printing work
            Single x = e.MarginBounds.Left;
            Single y = e.MarginBounds.Top;

            if (_pageNumber++ == 0)
                y += 30;

            RectangleF mainTextArea = RectangleF.FromLTRB(x, y, e.MarginBounds.Right, e.MarginBounds.Bottom);

            //draw the text
            if (DrawText(e.Graphics, e.PageSettings.PrinterSettings.CreateMeasurementGraphics(), mainTextArea, Brushes.Black))
            {
                e.HasMorePages = false; //the end has been reached
                _pageNumber = 0;
            }
            else
                e.HasMorePages = true;
        }
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        }

        #endregion
    }

    
}

           
          


Steps through the common dialogs. Does nothing else useful


   

/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// CmnDlgs.cs -- steps through the common dialogs. Does nothing else useful.
//
//               Compile this program with the following command line:
//                   C:>csc CmnDlgs.cs
using System;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace clsCommonDialogs
{
    public class CommonDialogs
    {
        [STAThread]
        static public void Main ()
        {
            // Create and display a Choose Color dialog box.
            ColorDialog cd = new ColorDialog ();
            cd.ShowDialog ();
            cd.Dispose ();
            
            // Create and display a Choose Font dialog box.
            FontDialog fd = new FontDialog ();
            fd.ShowDialog ();
            fd.Dispose ();
                
            // Create and display an Open File dialog box.
            OpenFileDialog ofd = new OpenFileDialog ();
            ofd.ShowDialog ();
            ofd.Dispose ();
            
            // Create and display a Save File dialog box.
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.ShowDialog ();
            sfd.Dispose ();
            
            // Create and display a Page Setup dialog box.
            PrintDocument printDoc = new PrintDocument();
            PageSetupDialog psd = new PageSetupDialog ();
            psd.Document = printDoc;
            psd.ShowDialog ();
            psd.Dispose ();
            
            // Create and display an Print dialog box.
            PrintDialog pd = new PrintDialog ();
            pd.Document = printDoc;
            pd.ShowDialog ();
            pd.Dispose ();
            
            // Create and display an Print Preview File dialog box.
            // This dialog is not a part of the common dialog library.
            PrintPreviewDialog ppd = new PrintPreviewDialog ();
            ppd.ShowDialog ();
            ppd.Dispose ();
            printDoc.Dispose ();
        }
    }
}


           
          


Using PrintPreviewDialog

   
 

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

using System.Drawing.Printing;

public class frmMain : System.Windows.Forms.Form {
    private System.Drawing.Printing.PrintDocument printDoc;
    private System.Windows.Forms.PrintPreviewDialog ppDialog;
    private System.Windows.Forms.Button btnPrint;
    public frmMain() {
        this.printDoc = new System.Drawing.Printing.PrintDocument();
        this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
        this.btnPrint = new System.Windows.Forms.Button();
        this.SuspendLayout();

        this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);

        this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
        this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
        this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
        this.ppDialog.Enabled = true;
        this.ppDialog.Location = new System.Drawing.Point(195, 22);
        this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
        this.ppDialog.Opacity = 1;
        this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
        this.ppDialog.Visible = false;

        this.btnPrint.Location = new System.Drawing.Point(52, 28);
        this.btnPrint.Text = "Print";
        this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(176, 86);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.btnPrint});
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.ResumeLayout(false);

    }
    [STAThread]
    static void Main() {
        Application.Run(new frmMain());
    }

    private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) {
        PrinterSettings pSettings = new PrinterSettings();
        Font printFont = new Font("Arial", 12);

        int nTextPosY = e.MarginBounds.Top;
        int nTextPosX = e.MarginBounds.Left;
        int nHeight = (int)printFont.GetHeight(e.Graphics);

        foreach (string sPtr in PrinterSettings.InstalledPrinters) {
            pSettings.PrinterName = sPtr;
            if (pSettings.IsValid) {
                e.Graphics.DrawString(sPtr, printFont, Brushes.Black, nTextPosX, nTextPosY + 5);
                e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
                e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 2));
                e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 3));
                e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 4));
                e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 5));
                e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 6));
                e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 7));
                e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
                    printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 8));
                nTextPosY = nTextPosY + ((5 + nHeight * 8) + nHeight);
            }
        }
    }
    private void btnPrint_Click(object sender, System.EventArgs e) {
        ppDialog.Document = printDoc;
        ppDialog.ShowDialog();
    }
}

    


Popup Menu action


   


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

  public class MainForm : System.Windows.Forms.Form
  {
    private int currFontSize = 20;

    private ContextMenu popUpMenu;

    private MenuItem currentCheckedItem;
    private MenuItem checkedHuge;
    private MenuItem checkedNormal;
    private MenuItem checkedTiny;

    public MainForm()
    {
      InitializeComponent();

      Text = "PopUp Menu";
      CenterToScreen();

      popUpMenu = new ContextMenu();

      popUpMenu.MenuItems.Add("Huge", new EventHandler(PopUp_Clicked));
      popUpMenu.MenuItems.Add("Normal", new EventHandler(PopUp_Clicked));
      popUpMenu.MenuItems.Add("Tiny", new EventHandler(PopUp_Clicked));


      this.ContextMenu = popUpMenu;

      checkedHuge = this.ContextMenu.MenuItems[0];
      checkedNormal = this.ContextMenu.MenuItems[1];        
      checkedTiny = this.ContextMenu.MenuItems[2];
      currentCheckedItem = checkedNormal;
      currentCheckedItem.Checked = true;

      this.Resize += new System.EventHandler(this.MainForm_Resize);
      this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint);

    }

    private void InitializeComponent()
    {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Text = "Form1";

    }

    static void Main() 
    {
      Application.Run(new MainForm());
    }
    private void PopUp_Clicked(object sender, EventArgs e) 
    {
      currentCheckedItem.Checked = false;

      MenuItem miClicked = (MenuItem)sender;
      string item = miClicked.Text;
      
      if(item == "Huge")
      {
        currFontSize = 30;
        currentCheckedItem = checkedHuge;
      }

      if(item == "Normal")
      {
        currFontSize = 20;
        currentCheckedItem = checkedNormal;
      }

      if(item == "Tiny")
      {
        currFontSize = 8;
        currentCheckedItem = checkedTiny;
      }
      currentCheckedItem.Checked = true;
      Invalidate();
        }

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
      Graphics g = e.Graphics;
      g.DrawString("Right click your mouse", 
        new Font("Times New Roman", (float)currFontSize), 
        new SolidBrush(Color.Black), 
        this.DisplayRectangle);
    }

    private void MainForm_Resize(object sender, System.EventArgs e)
    {
      Invalidate();
    }
  }


           
          


Dragging Images


   
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

public class MainForm : Form {
    private PictureBox happyBox = new PictureBox();
    private int oldX, oldY;
    private bool isDragging;
    private Rectangle dropRect = new Rectangle(100, 100, 140, 170);

    public MainForm() {
        happyBox.SizeMode = PictureBoxSizeMode.StretchImage;
        happyBox.Location = new System.Drawing.Point(64, 32);
        happyBox.Size = new System.Drawing.Size(50, 50);
        happyBox.Cursor = Cursors.Hand;
        happyBox.Image = new Bitmap("happyDude.bmp");
        happyBox.MouseDown += new MouseEventHandler(happyBox_MouseDown);
        happyBox.MouseUp += new MouseEventHandler(happyBox_MouseUp);
        happyBox.MouseMove += new MouseEventHandler(happyBox_MouseMove);
        Controls.Add(happyBox);

        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 361);
        this.Text = "Dragging Images";
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint);

    }

    void happyBox_MouseMove(object sender, MouseEventArgs e) {
        if (isDragging) {
            happyBox.Top = happyBox.Top + (e.Y - oldY);
            happyBox.Left = happyBox.Left + (e.X - oldX);
        }
    }

    void happyBox_MouseUp(object sender, MouseEventArgs e) {
        isDragging = false;
        if (dropRect.Contains(happyBox.Bounds))
            MessageBox.Show("You win!", "What an amazing test of skill...");
    }

    void happyBox_MouseDown(object sender, MouseEventArgs e) {
        isDragging = true;
        oldX = e.X;
        oldY = e.Y;
    }

    private void MainForm_Paint(object sender, PaintEventArgs e) {
        Graphics g = e.Graphics;
        g.FillRectangle(Brushes.BlueViolet, dropRect);
        g.DrawString("Drag the happy guy in here...",new Font("Times New Roman", 25), Brushes.WhiteSmoke, dropRect);
    }
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.Run(new MainForm());
    }
}

    


Subclass PictureBox

   
 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class PictureBoxPlusDemo: Form
{
     public static void Main()
     {
          Application.Run(new PictureBoxPlusDemo());
     }
     public PictureBoxPlusDemo()
     {
          Text = "PictureBoxPlus Demo";
   
          PictureBoxPlus picbox = new PictureBoxPlus();
          picbox.Parent = this;
          picbox.Dock = DockStyle.Fill;
          picbox.Image = Image.FromFile("Color.jpg");
     }
}
     class PictureBoxPlus: PictureBox
     {
          protected override void OnPaint(PaintEventArgs pea)
          {
               ScaleImageIsotropically(pea.Graphics, Image,ClientRectangle);
          }
          void ScaleImageIsotropically(Graphics grfx, Image image,
                                       Rectangle rect)
          {
               SizeF sizef = 
                    new SizeF(image.Width / image.HorizontalResolution,
                              image.Height / image.VerticalResolution);
   
               float fScale = Math.Min(rect.Width  / sizef.Width,
                                       rect.Height / sizef.Height);
   
               sizef.Width  *= fScale;
               sizef.Height *= fScale;
          
               grfx.DrawImage(image,
                              rect.X + (rect.Width  - sizef.Width ) / 2,
                              rect.Y + (rect.Height - sizef.Height) / 2,
                              sizef.Width, sizef.Height);
          }
     }