Как вставить картинку в windows form

Последнее обновление: 31.10.2015

Последнее обновление: 31.10.2015

PictureBox предназначен для показа изображений. Он позволяет отобразить файлы в формате bmp, jpg, gif, а также метафайлы ищображений
и иконки. Для установки изображения в PictureBox можно использовать ряд свойств:

  • Image: устанавливает объект типа Image

  • ImageLocation: устанавливает путь к изображению на диске или в интернете

  • InitialImage: некоторое начальное изображение, которое будет отображаться во время загрузки главного изображения,
    которое хранится в свойстве Image

  • ErrorImage: изображение, которое отображается, если основное изображение не удалось загрузить в PictureBox

Чтобы установить изображение в Visual Studio, надо в панели Свойств PictureBox выбрать свойство Image. В этом случае нам откроется окно импорта изображения
в проект, где мы собственно и сможем выбрать нужное изображение на компьютере и установить его для PictureBox:

Установка изображения для PictureBox

И затем мы сможем увидеть данное изображение в PictureBox:

Элемент PictureBox в Windows Forms

Либо можно загрузить изображение в коде:

pictureBox1.Image = Image.FromFile("C:UsersEugenePictures12.jpg");

Размер изображения

Для установки изображения в PictureBox используется свойство SizeMode, которое принимает следующие значения:

  • Normal: изображение позиционируется в левом верхнем углу PictureBox, и размер изображения не изменяется. Если
    PictureBox больше размеров изображения, то по справа и снизу появляются пустоты, если меньше — то изображение обрезается

  • StretchImage: изображение растягивается или сжимается таким обраом, чобы вместиться по всей ширине и высоте элемента PictureBox

  • AutoSize: элемент PictureBox автоматически растягивается, подстраиваясь под размеры изображения

  • CenterImage: если PictureBox меньше изображения, то изображение обрезается по краям и выводится только его центральная часть.
    Если же PictureBox больше изображения, то оно позиционируется по центру.

  • Zoom: изоражение подстраивается под размеры PictureBox, сохраняя при этом пропорции

Размер изображений в Windows Forms

I wanted to display an image to the windows forms, but i already did this and the image did not come out.

Where did I go wrong?

Here is the code:

private void Images(object sender, EventArgs e)
{
    PictureBox pb1 = new PictureBox();
    pb1.Image = Image.FromFile("../SamuderaJayaMotor.png");
    pb1.Location = new Point(100, 100);
    pb1.Size = new Size(500, 500);
    this.Controls.Add(pb1);
}

Lee Taylor's user avatar

Lee Taylor

7,65916 gold badges33 silver badges49 bronze badges

asked Oct 5, 2013 at 3:50

Kaoru's user avatar

1

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that «../SamuderaJayaMotor.png» is the correct path of the image that you are using.

4

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash () instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

answered Oct 5, 2013 at 3:54

dotNET's user avatar

dotNETdotNET

32.2k22 gold badges151 silver badges242 bronze badges

I display images in windows forms when I put it in Load event like this:

    private void Form1_Load( object sender , EventArgs e )
    {
        pictureBox1.ImageLocation = "./image.png"; //path to image
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

answered Jun 15, 2017 at 19:59

Iliyan's user avatar

IliyanIliyan

511 silver badge4 bronze badges

private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb = new PictureBox();
        pb.Location = new Point(0, 0);
        pb.Size = new Size(150, 150);
        pb.Image = Image.FromFile("E:\Wallpaper (204).jpg");
        pb.Visible = true;
        this.Controls.Add(pb);
    }

answered Jun 9, 2020 at 13:27

Alireza.m's user avatar

У многие новичков возникают вопросы при написании программа на C#. Один из часто задаваемых, как использовать компонент pictureBox и как использовать этот класс. Если вы пользуетесь конструктором в visual studio это одно, да вам легко перетащить из панели элементов pictureBox и в свойствах Image вставить изображение.  Но что делать если вам требуется изменить картинку программно, или вовсе при нажатии кнопки менять изображения. Вот об этом и поговорим в этой статье. Прежде всего вам потребуется сама картинка, я создал новое приложение назвал его pictureBox скачал из интернета 4 картинки, на форме разместил компонент pictureBox 150х150 и button. рис 1.

рис 1.

Теперь нам потребуется добавить наши картинки в проект, для это выбираем свойство нашего проекта рис 2.

рис 2.

Переходим во вкладку ресурсы, вверху окна выберем рядом со стрелочкой добавить ресурс, и жмем добавить существующий фаил, указываем наш фаил и он загружается в проект, по аналогии добавляем остальные картинки. рис. 3.

рис. 3

Молодцы теперь мы умеем добавлять ресурсы в наш проект, сюда так же можно добавлять и другого формата файлы, видео, музыку, текстовые файлы. Если вы были внимательны, то в обозревателе решений в папке Resources появились наши картинки. рис 3.

рис. 3

Теперь перейдем не посредственно коду программы, а именно одним из его свойств.

Свойство Image компонента PictureBox:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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 pictureBox

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

pictureBox1.Image = Properties.Resources.img1;

}

}

}

В коде программы мы видим что при нажатии на кнопку, мы переходим в обработчик событий button1_Click где вставляем в компонент pictureBox1 картинку, причем мы указываем полный путь к картинке, это папка свойства, ресурсы, img1. Теперь запустите наш пример и убедитесь что при нажатии на клавише у вас появилась картинка. Усложним нашу программы что бы изображения менялось на другие картинки при нажатии на кнопку, все строки я за комментировал что бы вам было легче разобраться.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

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 pictureBox

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

int count = 0;

private void button1_Click(object sender, EventArgs e)

{

count++; //тут я увеличиваю значения счетчика на 1

if (count == 1)

{

//если счетчик равен 1 то медведь

pictureBox1.Image = Properties.Resources.img1;

}

if (count == 2)

{

//если счетчик равен 2 то конь

pictureBox1.Image = Properties.Resources.img2;

}

if (count == 3)

{

//если счетчик равен 3 то щенок и котенок

pictureBox1.Image = Properties.Resources.img3;

}

if (count == 4)

{

//если счетчик равен 4 то тигренок

count = 0; //сбрасываем счетчки что бы начать все заново

pictureBox1.Image = Properties.Resources.img4;

}

}

}

}

Вот что должно было у вас получиться:

PictureBox кроме свойства Image которое с вами рассмотрели, имеет ряд свойств.

Свойство Size Определяет Width ширину  компонента, и Height высоту компонента, спомощью него можно задать размер и получить текущий размер PictureBox.

pictureBox1.Size = new System.Drawing.Size(150, 150); //задаем размеры

int h =pictureBox1.Size.Height; //получаем текущую высоту

int w = pictureBox1.Size.Width;//получаем текущую ширину

Свойство Location позволяет задать положения компонента на поверхности форму, с помощью приведенного ниже примера вы сможете разместить в любом месте на форме PictureBox.

pictureBox1.Location = new System.Drawing.Point(66, 42);

  • Remove From My Forums
  • Question

  • hi guys,

    how do i add an image or icon to my winform form ?

    e.g.  see this

    thanks

    Ehi

Answers

  • not really, e.g. in a webform you add the image control and then specify the path for the image.

    Likewise in the webform, I dont see any image control in the toolbox to add ???

    Its simply just to make it fancy, nothing more.

    Hi Ehioze,

    Welcome to the MSDN Forum.

    Maybe you want to draw the picture without any control, but show it as a background and you don’t want to set the background-Image, than you can do like the following sample:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            SetStyle(ControlStyles.ResizeRedraw, true);
    
            InitilizePicture();
        }
    
        Bitmap b = new Bitmap(1600, 900);
        Rectangle rect;
        Rectangle sourceRect;
        Image picture;
        Graphics g;
    
        private void InitilizePicture()
        {
            picture = Image.FromFile(Path.Combine(Environment.CurrentDirectory,"BG.jpg"));
            b.SetResolution(picture.HorizontalResolution, picture.VerticalResolution);
            g = Graphics.FromImage(b);
    
            rect = new Rectangle(0, 0,1600, 900);
          //  sourceRect = new Rectangle(new Point(0, 0), new Size(picture.Width, picture.Height));
            sourceRect = new Rectangle(0, 0, picture.Width, picture.Height);
    
            g.DrawImage(picture, rect, sourceRect, GraphicsUnit.Pixel);
        }
    
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            Close();
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.DrawImage(b, rect, sourceRect, GraphicsUnit.Pixel);
            base.OnPaint(e);
            
        }
    }
    

    And you can add a property  with set method so that you can change the image.

    On the other hand, you can also add the BackgroundImage by using the Visual Studio.

    Best Regards 


    Neddy Ren[MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by

      Thursday, November 24, 2011 9:16 AM

See how you can draw shapes, use colors, and render images in a WinForms app.

Computer sitting on table open to an image inside a software

Windows Forms is a framework that lets you build desktop applications. You can click and drag components like buttons onto a visual user interface. It also helps you manually create various shapes within your code.

This article will show you how to add lines, shapes, and images to your application. This tutorial uses the Visual Studio 2019 Community Edition to show examples.

What Are the Built-In Classes Used for Drawing Graphics?

Windows Forms uses the C# programming language. Its built-in classes and methods allow you to draw various shapes onto a Windows Form canvas. These include the Graphics, Pen, Color, and Brush classes.

Class

Description

Graphics

The Graphics class allows you to draw shapes and lines onto the canvas. It includes methods such as:

  • DrawLine(Pen, Point1, Point2)
  • DrawRectangle(x, y, width, height)
  • DrawPolygon(Pen, PointF[])

Pen

The Pen class allows you to specify the properties of a ‘pen’ tip which you can use to draw your shapes. You can specify properties such as color, thickness, or dash style. Methods include:

  • SetLineCap(LineCap, LineCap, DashCap)

Color

A color object made up of R (red), G (green), and B (blue) values. You will need a color object for many of the built-in methods that create shapes.

SolidBrush, HatchBrush, TextureBrush

These brush classes derive from the «Brush» interface. These classes allow you to color in blank spaces on the canvas. You can also choose to fill the spaces using different patterns or textures. You can specify properties such as the color.

Rectangle, Line, Polygon, Ellipse

You can create objects based on these shapes, and use them when calling methods such as DrawRectangle(). Instead of passing the x, y, width, and height as arguments, you can choose to pass an existing Rectangle object instead.

To view the source code for a running example of the above tutorial, visit the GitHub repository. You can try out the following examples once you’ve created a Winforms application.

How to Add a Paint on Form Load Event Handler

First, add an event handler to draw shapes when the canvas loads.

  1. Add a Paint function for the form.
     private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Code goes here
    }
  2. Go into the Design View Tab.
  3. In the Properties window, select the lightning icon to open the «Events» tab.
  4. In «Paint», under «Appearance», select the Form1_Paint function. This will execute the function when you run the application.
    Winforms showing how to add a paint event

How to Draw Lines Onto a Windows Form Canvas

You can use a Color, Pen, and the DrawLine() method to draw lines on a canvas.

  1. Inside the Form1_Paint() function, create a Color object with the color you want the line to be. Then, create a Pen object to draw the line with.
     Color black = Color.FromArgb(255, 0, 0, 0);
    Pen blackPen = new Pen(black);
  2. The DrawLine() method from the Graphics class will draw a line using the pen. This will start drawing a line from an x, y position to another x, y position.
     e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  3. You can modify the properties for the pen object to change its width, dash style, and start or end cap.
     blackPen.Width = 20;
    blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
    blackPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
    e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio App running with a line

How to Draw Shapes Such as Rectangles and Circles

You can use the shapes classes for different shapes, or draw shapes manually onto the canvas.

  1. Create a Color and Pen object as shown in the previous steps. Then, use the DrawRectangle() method to create the rectangle. The arguments are the x and y coordinates for the top-left of the rectangle, along with its width and height.
     Color red = Color.FromArgb(255, 255, 0, 0);
    Pen redPen = new Pen(red);
    redPen.Width = 5;
    e.Graphics.DrawRectangle(redPen, 100, 100, 500, 200);
  2. You can also create a rectangle using the Rectangle Class. First, create a Rectangle object. The arguments are also the x and y coordinates for the top-left corner, width, and height.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
  3. Use the DrawRectangle() function to draw the rectangle. Instead of passing the x, y, width, and height like before, you can use the Rectangle object instead.
     e.Graphics.DrawRectangle(redPen, rectangle);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio application running to show rectangles
  5. Go back to the code to draw other shapes. Use the DrawEllipse() function to draw a circle.
     Color green = Color.FromArgb(255, 0, 255, 0);
    Pen greenPen = new Pen(green);
    greenPen.Width = 5;
    e.Graphics.DrawEllipse(greenPen, 400, 150, 400, 400);

    When you draw a circle, the x and y coordinates (x=400, y=150) refer to the top-left corner of the circle, not the center of the circle.

    Close up example of circle on canvas and where X,Y starts
  6. To draw other shapes such as triangles or hexagons, use the DrawPolygon() method. Here you can specify a list of coordinates to represent the points of the shape.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Pen bluePen = new Pen(blue);
    bluePen.Width = 5;

    PointF[] coordinatesForTriangle = new PointF[] {
        new PointF(400, 150),
        new PointF(300, 300),
        new PointF(500, 300)
    };

    e.Graphics.DrawPolygon(bluePen, coordinatesForTriangle);

    The DrawPolygon() method will draw lines between the points specified.

    Visual Studio app running to show triangle on canvas

    ​​​​​​

How to Use the Brush Class to Fill In Shapes With Color

You can use the FillRectangle(), FillEllipses() or FillTriangle() methods to create shapes with a solid color.

  1. First, create a brush object.
     Color purple = Color.FromArgb(255, 128, 0, 0);
    SolidBrush solidBrush = new SolidBrush(purple);
  2. Use the FillRectangle(), FillEllipses() or FillTriangle() methods. They work the same way as the draw functions above, except instead of a Pen, they use a Brush object.
     e.Graphics.FillRectangle(solidBrush, 50, 50, 200, 250);
    e.Graphics.FillEllipse(solidBrush, 300, 50, 200, 200);
    e.Graphics.FillPolygon(solidBrush, new PointF[] { new PointF(700, 150), new PointF(600, 300), new PointF(800, 300) });
    Visual Studio app running to show filled shapes on canvas
  3. You can also input a shape object directly instead of providing coordinates.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
    e.Graphics.FillRectangle(solidBrush, rectangle);
  4. Use the HatchBrush to fill the shape using a different fill style, such as a horizontal or vertical pattern.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Color green = Color.FromArgb(255, 0, 255, 0);
    HatchBrush hatchBrush = new HatchBrush(HatchStyle.Horizontal, green, blue);
    e.Graphics.FillRectangle(hatchBrush, 50, 50, 200, 250);
    Visual Studio app open to show rectangle with horizontal pattern design fill
  5. You can use the TextureBrush to fill a shape using an image. Here, create a bitmap by pointing to an image file. Instead of creating a brush using a color, create it using the image.
     Bitmap image = (Bitmap)Image.FromFile(@"C:UsersSharlDesktopflag.bmp", true);
    TextureBrush textureBrush = new TextureBrush(image);
    e.Graphics.FillRectangle(textureBrush, 100, 100, 500, 400);
    Visual Studio app open to show shape filled using an image

How to Render Images Onto the Form

To render an image, create a PictureBox control object and add it to the form.

  1. Create a PictureBox control object using an image file.
     PictureBox picture = new PictureBox();
    picture.ImageLocation = @"C:UsersSharlDesktopflagLarge.bmp";
  2. Set the size of the image and add it onto the form so it renders.
     picture.SizeMode = PictureBoxSizeMode.AutoSize;
    this.Controls.Add(picture);
  3. Press the green start button at the top to view the image.
    Winforms App open to show image rendered on form

Adding More Shapes to Your Windows Form

You should now understand how to add lines, shapes, and images to your Windows form. You can combine shapes to create new shapes. You can also play around with the built-in functions to create more complex shapes.

See how you can draw shapes, use colors, and render images in a WinForms app.

Computer sitting on table open to an image inside a software

Windows Forms is a framework that lets you build desktop applications. You can click and drag components like buttons onto a visual user interface. It also helps you manually create various shapes within your code.

This article will show you how to add lines, shapes, and images to your application. This tutorial uses the Visual Studio 2019 Community Edition to show examples.

What Are the Built-In Classes Used for Drawing Graphics?

Windows Forms uses the C# programming language. Its built-in classes and methods allow you to draw various shapes onto a Windows Form canvas. These include the Graphics, Pen, Color, and Brush classes.

Class

Description

Graphics

The Graphics class allows you to draw shapes and lines onto the canvas. It includes methods such as:

  • DrawLine(Pen, Point1, Point2)
  • DrawRectangle(x, y, width, height)
  • DrawPolygon(Pen, PointF[])

Pen

The Pen class allows you to specify the properties of a ‘pen’ tip which you can use to draw your shapes. You can specify properties such as color, thickness, or dash style. Methods include:

  • SetLineCap(LineCap, LineCap, DashCap)

Color

A color object made up of R (red), G (green), and B (blue) values. You will need a color object for many of the built-in methods that create shapes.

SolidBrush, HatchBrush, TextureBrush

These brush classes derive from the «Brush» interface. These classes allow you to color in blank spaces on the canvas. You can also choose to fill the spaces using different patterns or textures. You can specify properties such as the color.

Rectangle, Line, Polygon, Ellipse

You can create objects based on these shapes, and use them when calling methods such as DrawRectangle(). Instead of passing the x, y, width, and height as arguments, you can choose to pass an existing Rectangle object instead.

To view the source code for a running example of the above tutorial, visit the GitHub repository. You can try out the following examples once you’ve created a Winforms application.

How to Add a Paint on Form Load Event Handler

First, add an event handler to draw shapes when the canvas loads.

  1. Add a Paint function for the form.
     private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Code goes here
    }
  2. Go into the Design View Tab.
  3. In the Properties window, select the lightning icon to open the «Events» tab.
  4. In «Paint», under «Appearance», select the Form1_Paint function. This will execute the function when you run the application.
    Winforms showing how to add a paint event

How to Draw Lines Onto a Windows Form Canvas

You can use a Color, Pen, and the DrawLine() method to draw lines on a canvas.

  1. Inside the Form1_Paint() function, create a Color object with the color you want the line to be. Then, create a Pen object to draw the line with.
     Color black = Color.FromArgb(255, 0, 0, 0);
    Pen blackPen = new Pen(black);
  2. The DrawLine() method from the Graphics class will draw a line using the pen. This will start drawing a line from an x, y position to another x, y position.
     e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  3. You can modify the properties for the pen object to change its width, dash style, and start or end cap.
     blackPen.Width = 20;
    blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
    blackPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
    e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio App running with a line

How to Draw Shapes Such as Rectangles and Circles

You can use the shapes classes for different shapes, or draw shapes manually onto the canvas.

  1. Create a Color and Pen object as shown in the previous steps. Then, use the DrawRectangle() method to create the rectangle. The arguments are the x and y coordinates for the top-left of the rectangle, along with its width and height.
     Color red = Color.FromArgb(255, 255, 0, 0);
    Pen redPen = new Pen(red);
    redPen.Width = 5;
    e.Graphics.DrawRectangle(redPen, 100, 100, 500, 200);
  2. You can also create a rectangle using the Rectangle Class. First, create a Rectangle object. The arguments are also the x and y coordinates for the top-left corner, width, and height.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
  3. Use the DrawRectangle() function to draw the rectangle. Instead of passing the x, y, width, and height like before, you can use the Rectangle object instead.
     e.Graphics.DrawRectangle(redPen, rectangle);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio application running to show rectangles
  5. Go back to the code to draw other shapes. Use the DrawEllipse() function to draw a circle.
     Color green = Color.FromArgb(255, 0, 255, 0);
    Pen greenPen = new Pen(green);
    greenPen.Width = 5;
    e.Graphics.DrawEllipse(greenPen, 400, 150, 400, 400);

    When you draw a circle, the x and y coordinates (x=400, y=150) refer to the top-left corner of the circle, not the center of the circle.

    Close up example of circle on canvas and where X,Y starts
  6. To draw other shapes such as triangles or hexagons, use the DrawPolygon() method. Here you can specify a list of coordinates to represent the points of the shape.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Pen bluePen = new Pen(blue);
    bluePen.Width = 5;

    PointF[] coordinatesForTriangle = new PointF[] {
        new PointF(400, 150),
        new PointF(300, 300),
        new PointF(500, 300)
    };

    e.Graphics.DrawPolygon(bluePen, coordinatesForTriangle);

    The DrawPolygon() method will draw lines between the points specified.

    Visual Studio app running to show triangle on canvas

    ​​​​​​

How to Use the Brush Class to Fill In Shapes With Color

You can use the FillRectangle(), FillEllipses() or FillTriangle() methods to create shapes with a solid color.

  1. First, create a brush object.
     Color purple = Color.FromArgb(255, 128, 0, 0);
    SolidBrush solidBrush = new SolidBrush(purple);
  2. Use the FillRectangle(), FillEllipses() or FillTriangle() methods. They work the same way as the draw functions above, except instead of a Pen, they use a Brush object.
     e.Graphics.FillRectangle(solidBrush, 50, 50, 200, 250);
    e.Graphics.FillEllipse(solidBrush, 300, 50, 200, 200);
    e.Graphics.FillPolygon(solidBrush, new PointF[] { new PointF(700, 150), new PointF(600, 300), new PointF(800, 300) });
    Visual Studio app running to show filled shapes on canvas
  3. You can also input a shape object directly instead of providing coordinates.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
    e.Graphics.FillRectangle(solidBrush, rectangle);
  4. Use the HatchBrush to fill the shape using a different fill style, such as a horizontal or vertical pattern.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Color green = Color.FromArgb(255, 0, 255, 0);
    HatchBrush hatchBrush = new HatchBrush(HatchStyle.Horizontal, green, blue);
    e.Graphics.FillRectangle(hatchBrush, 50, 50, 200, 250);
    Visual Studio app open to show rectangle with horizontal pattern design fill
  5. You can use the TextureBrush to fill a shape using an image. Here, create a bitmap by pointing to an image file. Instead of creating a brush using a color, create it using the image.
     Bitmap image = (Bitmap)Image.FromFile(@"C:UsersSharlDesktopflag.bmp", true);
    TextureBrush textureBrush = new TextureBrush(image);
    e.Graphics.FillRectangle(textureBrush, 100, 100, 500, 400);
    Visual Studio app open to show shape filled using an image

How to Render Images Onto the Form

To render an image, create a PictureBox control object and add it to the form.

  1. Create a PictureBox control object using an image file.
     PictureBox picture = new PictureBox();
    picture.ImageLocation = @"C:UsersSharlDesktopflagLarge.bmp";
  2. Set the size of the image and add it onto the form so it renders.
     picture.SizeMode = PictureBoxSizeMode.AutoSize;
    this.Controls.Add(picture);
  3. Press the green start button at the top to view the image.
    Winforms App open to show image rendered on form

Adding More Shapes to Your Windows Form

You should now understand how to add lines, shapes, and images to your Windows form. You can combine shapes to create new shapes. You can also play around with the built-in functions to create more complex shapes.

<< Back to C-SHARP

Use the PictureBox control from Windows Forms to render images.

PictureBox provides a rectangular region for an image. It supports many image formats. It has an adjustable size. It can access image files from your disk or from the Internet. It can resize images in several different ways.

Steps. First, the PictureBox provides a way to display an image. It can handle many different image formats. We use the PNG format. To add a PictureBox to your Windows Forms program, go to the Designer view and open the Toolbox.

Then: Drag the PictureBox icon to your window in the desired location. This creates a rectangular PictureBox instance.

In the next step of this tutorial, we assign an image to the PictureBox from the disk. There are several ways of doing this, but the way we use here allows you to quickly resize the PictureBox control so the entire image is shown.

Here: We use a PNG image in this code. But JPEG images and GIF images are also supported.

Event: We use the Form_Load event. To create this event handler, double-click on the enclosing window in the Designer view.

Windows Forms code that initialized PictureBox control: C#

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

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

private void Form1_Load(object sender, EventArgs e)
{
// Construct an image object from a file in the local directory.
// … This file must exist in the solution.
Image image = Image.FromFile(«BeigeMonitor1.png»);
// Set the PictureBox image property to this image.
// … Then, adjust its height and width properties.
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
}
}

The Image type is a class that encapsulates information about an image, including its data in bytes. It provides an abstract data type for handling an image in a clear way. It is found in the System.Drawing namespace.Image

Why assign the Height and Width? This code uses two statements to assign the Height and Width instance properties of the Image. This forces the PictureBox to resize correctly. If you omit these statements, the image may be cropped.

Also: It is easy to crop a PictureBox by setting its Width and Height to the desired values.

Discussion. At its core, the PictureBox is a mechanism for displaying an image graphically in the Windows Forms program. It cannot do elaborate transformations on this image. You must invoke any of these transformations through your own logic.

Tip: You can add hover (mouse-over) and click events to the PictureBox in the same way as other Windows Forms controls.

But: For complex programs that display images in a specific way, the PictureBox is not ideal.

PictureBoxSizeMode. Here we cover the transformations that are enabled through the SizeMode property on the PictureBox control. All of these settings affect how an image is displayed based on the dimensions of the control (width and height).

Instead of setting Width and Height, we can use the PictureBoxSizeMode.AutoSize enum. We can center the image both horizontally and vertically. We can stretch the image so that it fills the entire enclosing box.

And: We can zoom the image so that it maintains its original aspect ratio. The image does not appear distorted.

Enum values:

AutoSize
CenterImage
Normal
StretchImage
Zoom

ImageLocation. The PictureBox contains an instance property called ImageLocation, and this sets the image data from a file. If you use the AutoSize enum with the ImageLocation property, your PictureBox will be sized correctly.

Implementation of Form_Load: C#

private void Form1_Load(object sender, EventArgs e)
{
// Set the ImageLocation property to a file on the disk.
// … Set the size mode so that the image is correctly sized.
pictureBox1.ImageLocation = «BeigeMonitor1.png»;
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}

Download. For the PictureBox control, you can use the ImageLocation instance property to specify the URL of an image to download and place in the PictureBox. For this example, we will use the website icon file for this site.

Also: This example shows that the PictureBox supports the ICO format for images.

Another implementation of Form_Load: C#

private void Form1_Load(object sender, EventArgs e)
{
// Set the ImageLocation property to a URL.
// … This example image is tiny and is the icon for The Dev Codes.
pictureBox1.ImageLocation = «http://www.dotnetCodex.com/favicon.ico»;
}

Summary. The PictureBox displays images of various types. It handles the drawing of the pixels, and provides properties for adjusting the dimensions of the control. You can zoom images, stretch images, or crop image displays.

Related Links:

  • C# Array Examples, String Arrays
  • C# ArrayList Examples
  • C# ArraySegment: Get Array Range, Offset and Count
  • C# break Statement
  • C# Buffer BlockCopy Example
  • C# BufferedStream: Optimize Read and Write
  • 404 Not Found
  • C# 24 Hour Time Formats
  • C# 2D Array Examples
  • 7 Zip Command Line Examples
  • C# 7 Zip Executable (Process.Start)
  • C# All Method: All Elements Match a Condition
  • C# Alphabetize String
  • C# Alphanumeric Sorting
  • C# Arithmetic Expression Optimization
  • C# Array.AsReadOnly Method (ObjectModel)
  • C# Array.BinarySearch Method
  • C# Array.Clear Examples
  • C# Array.IndexOf, LastIndexOf: Search Arrays
  • C# async, await Examples
  • C# Attribute Examples
  • C# Average Method
  • C# BackgroundWorker
  • C# base Keyword
  • C# String Between, Before, After
  • C# Binary Representation int (Convert, toBase 2)
  • C# BinarySearch List
  • C# bool Array (Memory Usage, One Byte Per Element)
  • C# bool.Parse, TryParse: Convert String to Bool
  • C# bool Type
  • C# Array Length Property, Get Size of Array
  • C# Button Example
  • C# Byte Array: Memory Usage, Read All Bytes
  • C# Byte and sbyte Types
  • C# Capacity for List, Dictionary
  • C# Case Insensitive Dictionary
  • C# case Example (Switch Case)
  • C# Char Array
  • C# Checked and Unchecked Keywords
  • C# CheckedListBox: Windows Forms
  • C# Color Table
  • C# Color Examples: FromKnownColor, FromName
  • C# ColorDialog Example
  • C# Comment: Single Line and Multiline
  • C# Concat Extension: Combine Lists and Arrays
  • C# Conditional Attribute
  • C# Console Color, Text and BackgroundColor
  • C# String Clone() method
  • C# Constructor Examples
  • C# Contains Extension Method
  • C# String GetTypeCode() method
  • C# String ToLowerInvariant() method
  • C# Customized Dialog Box
  • C# DataColumn Example: Columns.Add
  • C# DataGridView Add Rows
  • DataGridView Columns, Edit Columns Dialog
  • C# DataGridView Row Colors (Alternating)
  • C# DataGridView Tutorial
  • C# DataGridView
  • C# DataRow Examples
  • C# DataSet Examples
  • C# DataSource Example
  • C# DataTable Compare Rows
  • C# DataTable foreach Loop
  • C# DataTable RowChanged Example: AcceptChanges
  • C# DataTable Select Example
  • C# DataTable Examples
  • C# DataView Examples
  • C# String ToString() method
  • C# String ToUpper() method
  • C# Digit Separator
  • C# DateTime.MinValue (Null DateTime)
  • C# DateTime.Month Property
  • C# DateTime.Parse: Convert String to DateTime
  • C# DateTime Subtract Method
  • C# Decompress GZIP
  • C# Remove Duplicates From List
  • C# dynamic Keyword
  • C# ElementAt, ElementAtOrDefault Use
  • C# Encapsulate Field
  • C# Enum Array Example, Use Enum as Array Index
  • C# enum Flags Attribute Examples
  • C# Enum ToString: Convert Enum to String
  • C# enum Examples
  • C# Enumerable.Range, Repeat and Empty
  • C# Environment Type
  • C# EventLog Example
  • C# Exception Handling
  • C# explicit and implicit Keywords
  • C# Factory Design Pattern
  • C# File.Copy Examples
  • C# typeof and nameof Operators
  • C# String TrimEnd() method
  • C# var Examples
  • C# virtual Keyword
  • C# void Method, Return No Value
  • C# volatile Example
  • C# WebBrowser Control (Navigate Method)
  • C# WebClient: DownloadData, Headers
  • C# Where Method and Keyword
  • C# String TrimStart() method
  • C# delegate Keyword
  • C# descending, ascending Keywords
  • C# while Loop Examples
  • C# Whitespace Methods: Convert UNIX, Windows Newlines
  • C# XmlReader, Parse XML File
  • C# XmlTextReader
  • C# XmlTextWriter
  • C# XmlWriter, Create XML File
  • C# XOR Operator (Bitwise)
  • C# yield Example
  • C# float Numbers
  • FlowLayoutPanel Control
  • C# Focused Property
  • C# FolderBrowserDialog Control
  • C# Font Type: FontFamily and FontStyle
  • C# FontDialog Example
  • C# for Loop Examples
  • C# foreach Loop Examples
  • ForeColor, BackColor: Windows Forms
  • C# Form: Event Handlers
  • C# Contains String Method
  • C# ContainsValue Method (Value Exists in Dictionary)
  • C# ContextMenuStrip Example
  • C# continue Keyword
  • C# Control: Windows Forms
  • C# Windows Forms Controls
  • C# Convert Char Array to String
  • C# Convert Char to String
  • C# Convert Days to Months
  • C# Convert String to Byte Array
  • C# String Format
  • C# Func Object (Lambda That Returns a Value)
  • C# GC.Collect Examples: CollectionCount, GetTotalMemory
  • C# Path.GetDirectoryName (Remove File From Path)
  • C# goto Examples
  • C# HttpClient Example: System.Net.Http
  • ASP.NET HttpContext Request Property
  • IL Disassembler Tutorial
  • C# Intermediate Language (IL)
  • C# IndexOf Examples
  • C# IndexOfAny Examples
  • C# Initialize Array
  • C# Initialize List
  • C# InitializeComponent Method: Windows Forms
  • C# Inline Optimization
  • C# Dictionary Equals: If Contents Are the Same
  • C# Dictionary Versus List Loop
  • C# Dictionary Order, Use Keys Added Last
  • C# Dictionary Size and Performance
  • C# Dictionary Versus List Lookup Time
  • C# Dictionary Examples
  • C# Get Directory Size (Total Bytes in All Files)
  • C# Directory Type
  • C# Distinct Method, Get Unique Elements Only
  • C# Divide by Powers of Two (Bitwise Shift)
  • C# Divide Numbers (Cast Ints)
  • C# DomainUpDown Control Example
  • C# Double Type: double.MaxValue, double.Parse
  • C# Remove Duplicate Chars
  • C# IEqualityComparer
  • C# If Preprocessing Directive: Elif and Endif
  • C# If Versus Switch Performance
  • C# if Statement
  • C# int.MaxValue, MinValue (Get Lowest Number)
  • C# Program to reverse number
  • C# Int and uint Types
  • C# Integer Append Optimization
  • C# Keywords
  • C# Label Example: Windows Forms
  • C# Lambda Expressions
  • C# LastIndexOf Examples
  • C# Last, LastOrDefault Methods
  • C# Mutex Example (OpenExisting)
  • C# Named Parameters
  • C# Let Keyword (Use Variable in Query Expression)
  • C# Levenshtein Distance
  • C# LinkLabel Example: Windows Forms
  • C# LINQ
  • C# List Add Method, Append Element to List
  • C# List AddRange, InsertRange (Append Array to List)
  • C# List Clear Example
  • C# List Contains Method
  • C# List Remove Examples
  • C# List Examples
  • C# ListBox Tutorial (DataSource, SelectedIndex)
  • C# ListView Tutorial: Windows Forms
  • C# Maze Pathfinding Algorithm
  • C# Memoization
  • C# Memory Usage for Arrays of Objects
  • C# MessageBox.Show Examples
  • C# Method Call Depth Performance
  • C# Method Parameter Performance
  • C# Method Size Optimization
  • C# Multidimensional Array
  • C# MultiMap Class (Dictionary of Lists)
  • C# Optimization
  • C# new Keyword
  • C# NotifyIcon: Windows Forms
  • C# NotImplementedException
  • C# Null Array
  • C# String GetType() method
  • C# Null Coalescing and Null Conditional Operators
  • C# Null List (NullReferenceException)
  • C# Numeric Casts
  • C# NumericUpDown Control: Windows Forms
  • C# object.ReferenceEquals Method
  • C# Object Examples
  • C# Optional Parameters
  • C# Prime Number
  • C# OrderBy, OrderByDescending Examples
  • C# Process Examples (Process.Start)
  • Panel, Windows Forms (Create Group of Controls)
  • C# Path Examples
  • C# Get Percentage From Number With Format String
  • ASP.NET PhysicalApplicationPath
  • C# PictureBox: Windows Forms
  • C# PNG Optimization
  • C# Position Windows: Use WorkingArea and Location
  • Visual Studio Post Build, Pre Build Macros
  • C# ProfileOptimization
  • C# ProgressBar Example
  • C# Property Examples
  • C# PropertyGrid: Windows Forms
  • C# Protected and internal Keywords
  • C# Public and private Methods
  • C# Remove Punctuation From String
  • C# Query Windows Forms (Controls.OfType)
  • C# Queryable: IQueryable Interface and AsQueryable
  • ASP.NET QueryString Examples
  • C# Queue Collection: Enqueue
  • C# RadioButton Use: Windows Forms
  • C# ReadOnlyCollection Use (ObjectModel)
  • C# Recursion Optimization
  • C# Recursive File List: GetFiles With AllDirectories
  • C# ref Keyword
  • C# Reflection Examples
  • C# Regex.Escape and Unescape Methods
  • C# StringBuilder Examples
  • C# StringComparison and StringComparer
  • C# StringReader Class (Get Parts of Strings)
  • C# String GetEnumerator() method
  • C# String GetHashCode() method
  • C# Regex Versus Loop: Use For Loop Instead of Regex
  • C# Regex.Match Examples: Regular Expressions
  • C# RemoveAll: Use Lambda to Delete From List
  • C# Replace String Examples
  • ASP.NET Response.BinaryWrite
  • ASP.NET Response.Write
  • C# Return Optimization: out Performance
  • C# SaveFileDialog: Use ShowDialog and FileName
  • C# Scraping HTML Links
  • C# sealed Keyword
  • C# Seek File Examples: ReadBytes
  • C# select new Example: LINQ
  • C# Select Method (Use Lambda to Modify Elements)
  • C# Serialize List (Write to File With BinaryFormatter)
  • C# Settings.settings in Visual Studio
  • C# Shuffle Array: KeyValuePair and List
  • C# Single and Double Types
  • C# Single Instance Windows Form
  • C# Snippet Examples
  • C# Sort DateTime List
  • C# Sort List With Lambda, Comparison Method
  • C# Sort Number Strings
  • C# Sort Examples: Arrays and Lists
  • C# SortedDictionary
  • C# SortedList
  • C# SortedSet Examples
  • C# Split String Examples
  • C# String Copy() method
  • C# SplitContainer: Windows Forms
  • C# SqlClient Tutorial: SqlConnection, SqlCommand
  • C# SqlCommand Example: SELECT TOP, ORDER BY
  • C# SqlCommandBuilder Example: GetInsertCommand
  • C# SqlConnection Example: Using, SqlCommand
  • C# SqlDataAdapter Example
  • C# SqlDataReader: GetInt32, GetString
  • C# SqlParameter Example: Constructor, Add
  • C# Stack Collection: Push, Pop
  • C# Static List: Global List Variable
  • C# Static Regex
  • C# Static String
  • C# static Keyword
  • C# StatusStrip Example: Windows Forms
  • C# String Chars (Get Char at Index)
  • C# string.Concat Examples
  • C# String Interpolation Examples
  • C# string.Join Examples
  • C# String Performance, Memory Usage Info
  • C# String Property
  • C# String Slice, Get Substring Between Indexes
  • C# String Switch Examples
  • C# String
  • C# StringBuilder Append Performance
  • C# StringBuilder Cache
  • C# ToBase64String (Data URI Image)
  • C# Struct Versus Class
  • C# struct Examples
  • C# Substring Examples
  • C# Numeric Suffix Examples
  • C# switch Examples
  • C# String IsNormalized() method
  • C# TabControl: Windows Forms
  • TableLayoutPanel: Windows Forms
  • C# Take and TakeWhile Examples
  • C# Task Examples (Task.Run, ContinueWith and Wait)
  • C# Ternary Operator
  • C# Text Property: Windows Forms
  • C# TextBox.AppendText Method
  • C# TextBox Example
  • C# TextChanged Event
  • C# TextFieldParser Examples: Read CSV
  • C# ThreadStart and ParameterizedThreadStart
  • C# throw Keyword Examples
  • C# Timer Examples
  • C# TimeSpan Examples
  • C# TrimEnd and TrimStart
  • C# True and False
  • C# Truncate String
  • C# String ToLower() method
  • C# String ToCharArray() method
  • C# String ToUpperInvariant() method
  • C# String Trim() method
  • C# Assign Variables Optimization
  • C# Array.Resize Examples
  • C# Array.Sort: Keys, Values and Ranges
  • C# Array.Reverse Example
  • C# Array Slice, Get Elements Between Indexes
  • C# Array.TrueForAll: Use Lambda to Test All Elements
  • C# ArrayTypeMismatchException
  • C# as: Cast Examples
  • C# ASCII Table
  • C# ASCII Transformation, Convert Char to Index
  • C# AsEnumerable Method
  • C# AsParallel Example
  • ASP.NET AspLiteral
  • C# BaseStream Property
  • C# Console.Beep Example
  • C# Benchmark
  • C# BinaryReader Example (Use ReadInt32)
  • C# BinaryWriter Type
  • C# BitArray Examples
  • C# BitConverter Examples
  • C# Bitcount Examples
  • C# Bool Methods, Return True and False
  • C# bool Sort Examples (True to False)
  • C# Caesar Cipher
  • C# Cast Extension: System.Linq
  • C# Cast to Int (Convert Double to Int)
  • C# Cast Examples
  • C# catch Examples
  • C# Change Characters in String (ToCharArray, For Loop)
  • C# Char Combine: Get String From Chars
  • C# char.IsDigit (If Char Is Between 0 and 9)
  • C# char.IsLower and IsUpper
  • C# Character Literal (const char)
  • C# Char Lowercase Optimization
  • C# Char Test (If Char in String Equals a Value)
  • C# char.ToLower and ToUpper
  • C# char Examples
  • C# abstract Keyword
  • C# Action Object (Lambda That Returns Void)
  • C# Aggregate: Use Lambda to Accumulate Value
  • C# AggressiveInlining: MethodImpl Attribute
  • C# Anagram Method
  • C# And Bitwise Operator
  • C# Anonymous Function (Delegate With No Name)
  • C# Any Method, Returns True If Match Exists
  • C# StringBuilder Append and AppendLine
  • C# StringBuilder AppendFormat
  • ASP.NET appSettings Example
  • C# ArgumentException: Invalid Arguments
  • C# Array.ConvertAll, Change Type of Elements
  • C# Array.Copy Examples
  • C# Array.CreateInstance Method
  • C# Array and Dictionary Test, Integer Lookups
  • C# Array.Exists Method, Search Arrays
  • C# Array.Find Examples, Search Array With Lambda
  • C# Array.ForEach: Use Lambda on Every Element
  • C# Array Versus List Memory Usage
  • C# Array Property, Return Empty Array
  • C# CharEnumerator
  • C# Chart, Windows Forms (Series and Points)
  • C# CheckBox: Windows Forms
  • C# class Examples
  • C# Clear Dictionary: Remove All Keys
  • C# Clone Examples: ICloneable Interface
  • C# Closest Date (Find Dates Nearest in Time)
  • C# Combine Arrays: List, Array.Copy and Buffer.BlockCopy
  • C# Combine Dictionary Keys
  • C# ComboBox: Windows Forms
  • C# CompareTo Int Method
  • C# Comparison Object, Used With Array.Sort
  • C# Compress Data: GZIP
  • C# Console.Read Method
  • C# Console.ReadKey Example
  • C# Console.ReadLine Example (While Loop)
  • C# Console.SetOut and Console.SetIn
  • C# Console.WindowHeight
  • C# Console.Write, Append With No Newline
  • C# Console.WriteLine (Print)
  • C# const Example
  • C# Constraint Puzzle Solver
  • C# Count Characters in String
  • C# Count, Dictionary (Get Number of Keys)
  • C# Count Letter Frequencies
  • C# Count Extension Method: Use Lambda to Count
  • C# CSV Methods (Parse and Segment)
  • C# DataRow Field Method: Cast DataTable Cell
  • C# Get Day Count Elapsed From DateTime
  • C# DateTime Format
  • C# DateTime.Now (Current Time)
  • C# DateTime.Today (Current Day With Zero Time)
  • C# DateTime.TryParse and TryParseExact
  • C# DateTime Examples
  • C# DateTimePicker Example
  • C# Debug.Write Examples
  • C# Visual Studio Debugging Tutorial
  • C# decimal Examples
  • C# DayOfWeek
  • C# Enum.Format Method (typeof Enum)
  • C# Enum.GetName, GetNames: Get String Array From Enum
  • C# Enum.Parse, TryParse: Convert String to Enum
  • C# Error and Warning Directives
  • C# ErrorProvider Control: Windows Forms
  • C# event Examples
  • C# Get Every Nth Element From List (Modulo)
  • C# Excel Interop Example
  • C# Except (Remove Elements From Collection)
  • C# Extension Method
  • C# extern alias Example
  • C# Convert Feet, Inches
  • C# File.Delete
  • C# File Equals: Compare Files
  • C# File.Exists Method
  • C# try Keyword
  • C# TryGetValue (Get Value From Dictionary)
  • C# Tuple Examples
  • C# Type Class: Returned by typeof, GetType
  • C# TypeInitializationException
  • C# Union: Combine and Remove Duplicate Elements
  • C# Unreachable Code Detected
  • C# Unsafe Keyword: Fixed, Pointers
  • C# Uppercase First Letter
  • C# Uri and UriBuilder Classes
  • C# Using Alias Example
  • C# using Statement: Dispose and IDisposable
  • C# value Keyword
  • C# ValueTuple Examples (System.ValueTuple, ToTuple)
  • C# ValueType Examples
  • C# Variable Initializer for Class Field
  • C# Word Count
  • C# Word Interop: Microsoft.Office.Interop.Word
  • C# XElement Example (XElement.Load, XName)
  • C# Zip Method (Use Lambda on Two Collections)
  • C# File.Move Method, Rename File
  • C# File.Open Examples
  • C# File.ReadAllBytes, Get Byte Array From File
  • C# File.ReadAllLines, Get String Array From File
  • C# File.ReadAllText, Get String From File
  • C# File.ReadLines, Use foreach Over Strings
  • C# File.Replace Method
  • C# FileInfo Length, Get File Size
  • C# FileInfo Examples
  • C# File Handling
  • C# Filename With Date Example (DateTime.Now)
  • C# FileNotFoundException (catch Example)
  • C# FileStream Length, Get Byte Count From File
  • C# FileStream Example, File.Create
  • C# FileSystemWatcher Tutorial (Changed, e.Name)
  • C# finally Keyword
  • C# First Sentence
  • C# FirstOrDefault (Get First Element If It Exists)
  • C# Fisher Yates Shuffle: Generic Method
  • C# fixed Keyword (unsafe)
  • C# Flatten Array (Convert 2D to 1D)
  • C# First Words in String
  • C# First (Get Matching Element With Lambda)
  • C# ContainsKey Method (Key Exists in Dictionary)
  • C# Convert ArrayList to Array (Use ToArray)
  • C# Convert ArrayList to List
  • C# Convert Bool to Int
  • C# Convert Bytes to Megabytes
  • C# Convert Degrees Celsius to Fahrenheit
  • C# Convert Dictionary to List
  • C# Convert Dictionary to String (Write to File)
  • C# Convert List to Array
  • C# Convert List to DataTable (DataGridView)
  • C# Convert List to String
  • C# Convert Miles to Kilometers
  • C# Convert Milliseconds, Seconds, Minutes
  • C# Convert Nanoseconds, Microseconds, Milliseconds
  • C# Convert String Array to String
  • C# Convert TimeSpan to Long
  • C# Convert Types
  • C# Copy Dictionary
  • C# Count Elements in Array and List
  • C# FromOADate and Excel Dates
  • C# Generic Class, Generic Method Examples
  • C# GetEnumerator: While MoveNext, Get Current
  • C# GetHashCode (String Method)
  • C# Thumbnail Image With GetThumbnailImage
  • C# GetType Method
  • C# Global Variable Examples (Public Static Property)
  • ASP.NET Global Variables Example
  • C# Group By Operator: LINQ
  • GroupBox: Windows Forms
  • C# GroupBy Method: LINQ
  • C# GroupJoin Method
  • C# GZipStream Example (DeflateStream)
  • C# HashSet Examples
  • C# Hashtable Examples
  • HelpProvider Control Use
  • C# HTML and XML Handling
  • C# HtmlEncode and HtmlDecode
  • C# HtmlTextWriter Example
  • C# HttpUtility.HtmlEncode Methods
  • C# HybridDictionary
  • C# default Operator
  • C# DefaultIfEmpty Method
  • C# Define and Undef Directives
  • C# Destructor
  • C# DialogResult: Windows Forms
  • C# Dictionary, Read and Write Binary File
  • C# Dictionary Memory
  • C# Dictionary Optimization, Increase Capacity
  • C# Dictionary Optimization, Test With ContainsKey
  • C# DictionaryEntry Example (Hashtable)
  • C# Directives
  • C# Directory.CreateDirectory, Create New Folder
  • C# Directory.GetFiles Example (Get List of Files)
  • C# DivideByZeroException
  • C# DllImport Attribute
  • C# Do While Loop Example
  • C# DriveInfo Examples
  • C# DropDownItems Control
  • C# IComparable Example, CompareTo: Sort Objects
  • C# IDictionary Generic Interface
  • C# IEnumerable Examples
  • C# IList Generic Interface: List and Array
  • C# Image Type
  • C# ImageList Use: Windows Forms
  • C# Increment String That Contains a Number
  • C# Increment, Preincrement and Decrement Ints
  • Dot Net Perls
  • C# Indexer Examples (This Keyword, get and set)
  • C# IndexOutOfRangeException
  • C# Inheritance
  • C# Insert String Examples
  • C# int Array
  • C# Interface Examples
  • C# Interlocked Examples: Add, CompareExchange
  • C# Intersect: Get Common Elements
  • C# InvalidCastException
  • C# InvalidOperationException: Collection Was Modified
  • C# IOException Type: File, Directory Not Found
  • C# IOrderedEnumerable (Query Expression With orderby)
  • C# is: Cast Examples
  • C# IsFixedSize, IsReadOnly and IsSynchronized Arrays
  • C# string.IsNullOrEmpty, IsNullOrWhiteSpace
  • C# IsSorted Method: If Array Is Already Sorted
  • C# Jagged Array Examples
  • C# join Examples (LINQ)
  • C# KeyCode Property and KeyDown
  • C# KeyNotFoundException: Key Not Present in Dictionary
  • C# KeyValuePair Examples
  • C# Line Count for File
  • C# Line Directive
  • C# LinkedList
  • C# List CopyTo (Copy List Elements to Array)
  • C# List Equals (If Elements Are the Same)
  • C# List Find and Exists Examples
  • C# List Insert Performance
  • ASP.NET LiteralControl Example
  • C# Locality Optimizations (Memory Hierarchy)
  • C# lock Keyword
  • C# Long and ulong Types
  • C# Loop Over String Chars: Foreach, For
  • C# Loop Over String Array
  • C# Main args Examples
  • C# Map Example
  • ASP.NET MapPath: Virtual and Physical Paths
  • C# Mask Optimization
  • C# MaskedTextBox Example
  • C# Math.Abs: Absolute Value
  • C# Math.Ceiling Usage
  • C# Math.Floor Method
  • C# Math.Max and Math.Min Examples
  • C# Math.Pow Method, Exponents
  • C# Math.Round Examples: MidpointRounding
  • C# Math Type
  • C# Max and Min: Get Highest or Lowest Element
  • C# MemoryFailPoint and InsufficientMemoryException
  • C# MemoryStream: Use Stream on Byte Array
  • C# MenuStrip: Windows Forms
  • C# Modulo Operator: Get Remainder From Division
  • C# MonthCalendar Control: Windows Forms
  • C# Multiple Return Values
  • C# Multiply Numbers
  • C# namespace Keyword
  • C# NameValueCollection Usage
  • C# Nested Lists: Create 2D List or Jagged List
  • C# Nested Switch Statement
  • C# Environment.NewLine
  • C# Normalize, IsNormalized Methods
  • C# Null String Example
  • C# null Keyword
  • C# Nullable Examples
  • C# NullReferenceException and Null Parameter
  • C# Object Array
  • C# Obsolete Attribute
  • C# OfType Examples
  • C# OpenFileDialog Example
  • C# operator Keyword
  • C# Odd and Even Numbers
  • C# Bitwise Or
  • C# orderby Query Keyword
  • C# out Parameter
  • C# OutOfMemoryException
  • C# OverflowException
  • C# Overload Method
  • C# Override Method
  • C# PadRight and PadLeft: String Columns
  • C# Get Paragraph From HTML With Regex
  • C# Parallel.For Example (Benchmark)
  • C# Parallel.Invoke: Run Methods on Separate Threads
  • C# Parameter Optimization
  • C# Parameter Passing, ref and out
  • C# params Keyword
  • C# int.Parse: Convert Strings to Integers
  • C# partial Keyword
  • C# Path.ChangeExtension
  • C# Path Exists Example
  • C# Path.GetExtension: File Extension
  • C# Path.GetRandomFileName Method
  • C# Pragma Directive
  • C# Predicate (Lambda That Returns True or False)
  • C# Pretty Date Format (Hours or Minutes Ago)
  • C# PreviewKeyDown Event
  • C# Random Lowercase Letter
  • C# Random Paragraphs and Sentences
  • C# Random String
  • C# Random Number Examples
  • C# StreamReader ReadLine, ReadLineAsync Examples
  • C# readonly Keyword
  • C# Recursion Example
  • C# Regex, Read and Match File Lines
  • C# Regex Groups, Named Group Example
  • C# Regex.Matches Quote Example
  • C# Regex.Matches Method: foreach Match, Capture
  • C# Regex.Replace, Matching End of String
  • C# Regex.Replace, Remove Numbers From String
  • C# Regex.Replace, Merge Multiple Spaces
  • C# Regex.Replace Examples: MatchEvaluator
  • C# Regex.Split, Get Numbers From String
  • C# Regex.Split Examples
  • C# Regex Trim, Remove Start and End Spaces
  • C# RegexOptions.Compiled
  • C# RegexOptions.IgnoreCase Example
  • C# RegexOptions.Multiline
  • C# Region and endregion
  • C# Remove Char From String at Index
  • C# Remove Element
  • C# Remove HTML Tags
  • C# Remove String
  • C# Reserved Filenames
  • C# return Keyword
  • C# Reverse String
  • C# Reverse Words
  • C# Reverse Extension Method
  • C# RichTextBox Example
  • C# Right String Part
  • C# RNGCryptoServiceProvider Example
  • C# ROT13 Method, Char Lookup Table
  • C# SelectMany Example: LINQ
  • C# Sentinel Optimization
  • C# SequenceEqual Method (If Two Arrays Are Equal)
  • C# Shift Operators (Bitwise)
  • C# Short and ushort Types
  • C# Single Method: Get Element If Only One Matches
  • C# SingleOrDefault
  • C# Singleton Pattern Versus Static Class
  • C# Singleton Class
  • C# sizeof Keyword
  • C# Skip and SkipWhile Examples
  • C# Sleep Method (Pause)
  • C# Sort Dictionary: Keys and Values
  • C# Sort by File Size
  • C# Sort, Ignore Leading Chars
  • C# Sort KeyValuePair List: CompareTo
  • C# Sort Strings by Length
  • C# Thread.SpinWait Example
  • C# Math.Sqrt Method
  • C# stackalloc Operator
  • C# StackOverflowException
  • C# StartsWith and EndsWith String Methods
  • C# Static Array
  • C# Static Dictionary
  • C# Stopwatch Examples
  • C# Stream
  • C# StreamReader ReadToEnd Example (Read Entire File)
  • C# StreamReader ReadToEndAsync Example (Performance)
  • C# StreamReader Examples
  • C# StreamWriter Examples
  • C# String Append (Add Strings)
  • C# String Compare and CompareTo Methods
  • C# String Constructor (new string)
  • C# string.Copy Method
  • C# CopyTo String Method: Put Chars in Array
  • C# Empty String Examples
  • C# String Equals Examples
  • C# String For Loop, Count Spaces in String
  • C# string.Intern and IsInterned
  • C# String IsUpper, IsLower
  • C# String Length Property: Get Character Count
  • C# String Literal: Newline and Quote Examples
  • C# StringBuilder Capacity
  • C# StringBuilder Clear (Set Length to Zero)
  • C# StringBuilder Data Types
  • C# StringBuilder Performance
  • C# StringBuilder Equals (If Chars Are Equal)
  • C# StringBuilder Memory
  • C# StringBuilder ToString: Get String From StringBuilder
  • C# StringWriter Class
  • C# Sum Method: Add up All Numbers
  • C# Switch Char, Test Chars With Cases
  • C# Switch Enum
  • C# System (using System namespace)
  • C# Tag Property: Windows Forms
  • C# TextInfo Examples
  • C# TextReader, Returned by File.OpenText
  • C# TextWriter, Returned by File.CreateText
  • C# this Keyword
  • C# ThreadPool
  • C# Thread Join Method (Join Array of Threads)
  • C# ThreadPool.SetMinThreads Method
  • C# TimeZone Examples
  • C# Get Title From HTML With Regex
  • C# ToArray Extension Method
  • C# ToCharArray: Convert String to Array
  • C# ToDictionary Method
  • C# Token
  • C# ToList Extension Method
  • C# ToLookup Method (Get ILookup)
  • C# ToLower and ToUpper: Uppercase and Lowercase Strings
  • ToolStripContainer Control: Dock, Properties
  • C# ToolTip: Windows Forms
  • C# ToString Integer Optimization
  • C# ToString: Get String From Object
  • C# ToTitleCase Method
  • C# TrackBar: Windows Forms
  • C# Tree and Nodes Example: Directed Acyclic Word Graph
  • C# TreeView Tutorial
  • C# Trim Strings
  • C# Thread Methods
  • C# History
  • C# Features
  • C# Variables
  • C# Data Types
  • C# Operators
  • C# Keywords
  • C# New Features | C# Version Features
  • C# Programs
  • C# Program to swap numbers without third variable
  • C# Program to convert Decimal to Binary
  • C# Program to Convert Number in Characters
  • C# Program to Print Alphabet Triangle
  • C# Program to print Number Triangle
  • C# Program to generate Fibonacci Triangle
  • C# String Compare() method
  • C# String CompareOrdinal() method
  • C# String CompareTo() method
  • C# String Concat() method
  • C# String Contains() method
  • C# String CopyTo() method
  • C# String EndsWith() method
  • C# String Equals() method
  • C# String Format() method
  • C# String IndexOf() method
  • C# String Insert() method
  • C# String Intern(String str) method
  • C# String IsInterned() method
  • C# String Normalize() method
  • C# String IsNullOrEmpty() method
  • C# String IsNullOrWhiteSpace() method
  • C# String Join() method
  • C# String LastIndexOf() method
  • C# String LastIndexOfAny() method
  • C# String PadLeft() method
  • C# String PadRight() method
  • C# Nullable
  • C# String Remove() method
  • C# String Replace() method
  • C# String Split() method
  • C# String StartsWith() method
  • C# String SubString() method
  • C# Partial Types
  • C# Iterators
  • C# Delegate Covariance
  • C# Delegate Inference
  • C# Anonymous Types
  • C# Extension Methods
  • C# Query Expression
  • C# Partial Method
  • C# Implicitly Typed Local Variable
  • C# Object and Collection Initializer
  • C# Auto Implemented Properties
  • C# Dynamic Binding
  • C# Named and Optional Arguments
  • C# Asynchronous Methods
  • C# Caller Info Attributes
  • C# Using Static Directive
  • C# Exception Filters
  • C# Await in Catch Finally Blocks
  • C# Default Values for Getter Only Properties
  • C# Expression Bodied Members
  • C# Null Propagator
  • C# String Interpolation
  • C# nameof operator
  • C# Dictionary Initializer
  • C# Pattern Matching
  • C# Tuples
  • C# Deconstruction
  • C# Local Functions
  • C# Binary Literals
  • C# Ref Returns and Locals
  • C# Expression Bodied Constructors and Finalizers
  • C# Expression Bodied Getters and Setters
  • C# Async Main
  • C# Default Expression

Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

Понравилась статья? Поделить с друзьями:
  • Как вставить изображение в windows movie maker
  • Как вставить драйвера в образ windows 7
  • Как вставить видео в windows forms
  • Как вставить видео в powerpoint windows 10
  • Как вставить в консоль скопированный текст windows