[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a button display the picture beneath it in C#

[Make a button display the picture beneath it in C#]

This example makes a button display copies of the picture on which it sits, making it appear that the button is part of the underlying image.

The key to this example is the following SetButtonBackground method.

// Make the Button display the part of the // PictureBox's picture that is under it. private void SetButtonBackground(PictureBox pic, Button btn) { // Get the offset between the PictureBox's // and button's upper left corners. Point pic_pt = new Point(0, 0); pic_pt = pic.PointToScreen(pic_pt); Point btn_pt = new Point(0, 0); btn_pt = btn.PointToScreen(btn_pt); int x_offset = btn_pt.X - pic_pt.X; int y_offset = btn_pt.Y - pic_pt.Y; // Get the button's size. int wid = btn.ClientSize.Width; int hgt = btn.ClientSize.Height; // Make a bitmap to hold the button image. Bitmap bm = new Bitmap(wid, hgt); using (Graphics gr = Graphics.FromImage(bm)) { // Destination rectangle. Rectangle dest_rect = new Rectangle(0, 0, wid, hgt); // Source rectangle. Rectangle src_rect = new Rectangle(x_offset, y_offset, wid, hgt); // Copy the image under the button into the bitmap. gr.DrawImage(pic.Image, dest_rect, src_rect, GraphicsUnit.Pixel); } // Make the button display the image. btn.Image = bm; }

The method starts by using the PointToScreen method to determine where the upper left corner of the PictureBox and Button are in screen coordinates. This gives the relative offset between the two controls in pixels.

The code then gets the button's size, makes a Bitmap to fit it, and creates an associated Graphics object.

Next, the method makes Rectangle structures to define the source and destination areas in the PictureBox control's image that should be copied to the button. It then uses the Graphics object's DrawImage method to copy that part of the PictureBox image into the new Bitmap. It finishes by making the Button display the new Bitmap.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.