How to change the border color of a picturebox (winform)?

左心房为你撑大大i 提交于 2020-02-23 09:51:29

问题


I want to set the border color/style around the picturebox on and off according to different events.

Are there properties or functions that help me to achieve that aim?


回答1:


Winforms doesn't let you change the border color of controls, they are fixed by the theme selected by the user. The easiest way to get what you want that doesn't require writing your own control is to put the picture box inside of a Panel, making it slightly smaller. Then just change the BackColor of the panel.

The designer will fight you a bit since it tries to align controls to a grid, edit the Location and Size properties in the Properties window directly rather than mousing it.




回答2:


This has always been what I use for that:

To change the border color, call this from the Paint event handler of your Picturebox control:

private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {
        ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
    }

To change the border color dynamically, for instance from a mouseclick event, I use the Tag property of the picturebox to store the color and adjust the Click event of the picturebox to retrieve it from there. For example:

  if (pictureBox1.Tag == null) { pictureBox1.Tag = Color.Red; } //Sets a default color
  ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, (Color)pictureBox1.Tag, ButtonBorderStyle.Solid);

The picturebox Click event, then, would go something like this:

private void pictureBox1_Click(object sender, EventArgs e)
        {
            if ((Color)pictureBox1.Tag == Color.Red) { pictureBox1.Tag = Color.Blue; }
            else {pictureBox1.Tag = Color.Red; }
            pictureBox1.Refresh();
        }

You'll need using System.Drawing; at the beginning and don't forget to call pictureBox1.Refresh() at the end. Enjoy!




回答3:


Here is a simple example (in VB.NET, but it should be simple to convert it) that does this for you. You won't need to worry with using an extra Panel like with Passant's answer.




回答4:


If you are talking about mouse events then MouseEnter and MouseLeave or MouseHover events can be utilized to do this and OnPaint event can be used to do the actual drawing. just invalidate the PictureBox on Above mentioned Mouse events or any event you care about.



来源:https://stackoverflow.com/questions/5290601/how-to-change-the-border-color-of-a-picturebox-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!