How to change the color of Tab Control (in c#)

Hi,
The Tab Control in .net does not expose properties to change its back ground and foreground color. This can be achieved by overriding the DrawItem event of the control. Following are the steps involved to do the same.
1. Set the TabControl's DrawMode to OwnerDraw
2. Handle the DrawItem event to draw things yourself
You may call the following method at the DrawItem event of tab control to test this.

        private void ChangeTabColor(DrawItemEventArgs e)
        {
            Font TabFont;
            Brush BackBrush = new SolidBrush(Color.Green); //Set background color
            Brush ForeBrush = new SolidBrush(Color.Yellow);//Set foreground color
            if (e.Index == this.tabControl1.SelectedIndex)
            {
                TabFont = new Font(e.Font, FontStyle.Italic FontStyle.Bold);
            }
            else
            {
                TabFont = e.Font;
            }
            string TabName = this.tabControl1.TabPages[e.Index].Text;
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            e.Graphics.FillRectangle(BackBrush, e.Bounds);
            Rectangle r = e.Bounds;
            r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
            e.Graphics.DrawString(TabName, TabFont, ForeBrush, r, sf);
            //Dispose objects
            sf.Dispose();
            if (e.Index == this.tabControl1.SelectedIndex)
            {
                TabFont.Dispose();
                BackBrush.Dispose();
            }
            else
            {
                BackBrush.Dispose();
                ForeBrush.Dispose();
            }
        }


 

'.Net > Winform' 카테고리의 다른 글

C# 사용자별 개별 저장소 제공하기  (0) 2012.12.21
C# ListBox Height 변경하기  (1) 2012.12.14
C# 디스플레이 정보 가져오기  (0) 2012.12.06
C# Color->Brush  (0) 2012.11.26
C# RectangleShape 색 채우기  (0) 2012.11.23

Screen 클래스

 

속성

이름

설명

AllScreens

시스템의 모든 디스플레이 배열을 가져옵니다.

BitsPerPixel

1 픽셀의 데이터와 연결 된 메모리의 비트 수를 가져옵니다.

Bounds

디스플레이의 범위를 가져옵니다.

DeviceName

디스플레이와 관련 된 장치 이름을 가져옵니다.

Primary

특정 디스플레이가 기본 장치 인지 여부를 나타내는 값을 가져옵니다.

PrimaryScreen

기본 디스플레이 가져옵니다.

WorkingArea

디스플레이의 작업 영역을 가져옵니다.작업 영역 작업 표시줄, 도킹 된 창 및 도킹 된 도구 모음을 제외한 디스플레이의 데스크톱 영역이입니다.

 

메서드

이름

설명

Equals

지정 된 개체를이 같은지 여부를 나타내는 값을 가져오거나 설정 합니다. Screen. (Object.Equals(Object)() 재정의함)

Finalize

가비지 수집자 에서 회수하기 전에 개체에서 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다.

(Object에서 상속됨)

FromControl

검색은 Screen 에 지정 된 컨트롤의 가장 큰 부분을 들어 표시.

FromHandle

검색은 Screen 개체의 가장 큰 부분을 들어 표시에 대 한 지정 된 핸들에 의해 참조 됩니다.

FromPoint

검색은 Screen 지정 된 지점에 표시 하기 위한.

FromRectangle

검색은 Screen 사각형의 가장 큰 부분을 들어 표시 합니다.

GetBounds(Control)

지정 된 컨트롤의 가장 큰 부분을 포함 하는 디스플레이의 범위를 검색 합니다.

GetBounds(Point)

지정한 지점을 포함 하는 디스플레이의 범위를 검색 합니다.

GetBounds(Rectangle)

지정 된 사각형의 가장 큰 부분을 포함 하는 디스플레이의 범위를 검색 합니다.

GetHashCode

계산 하는 개체의 해시 코드를 검색 합니다. (Object.GetHashCode()() 재정의함)

GetType

현재 인스턴스의 Type을 가져옵니다. (Object에서 상속됨)

GetWorkingArea(Control)

가장 큰 영역이 지정 된 컨트롤에 표시 하기 위한 작업 영역을 검색 합니다.작업 영역 작업 표시줄, 도킹 된 창 및 도킹 된 도구 모음을 제외한 디스플레이의 데스크톱 영역이입니다.

GetWorkingArea(Point)

지정 된 위치에 가장 가까운 작업 영역을 검색합니다.작업 영역 작업 표시줄, 도킹 된 창 및 도킹 된 도구 모음을 제외한 디스플레이의 데스크톱 영역이입니다.

GetWorkingArea(Rectangle)

지정 된 사각형의 가장 큰 부분을 포함 하는 디스플레이 대 한 작업 영역을 검색 합니다.작업 영역 작업 표시줄, 도킹 된 창 및 도킹 된 도구 모음을 제외한 디스플레이의 데스크톱 영역이입니다.

MemberwiseClone

현재 Object의 단순 복사본을 만듭니다. (Object에서 상속됨)

ToString

이 개체를 나타내는 문자열을 검색 합니다. (Object.ToString()() 재정의함)

 

출처 : http://msdn.microsoft.com/ko-kr/library/system.windows.forms.screen.aspx

'.Net > Winform' 카테고리의 다른 글

C# ListBox Height 변경하기  (1) 2012.12.14
C# TabControl Tab Background 변경  (0) 2012.12.11
C# Color->Brush  (0) 2012.11.26
C# RectangleShape 색 채우기  (0) 2012.11.23
C# 임시폴더, 임시파일 이름 얻기  (0) 2012.11.22
new SolidBrush(label.DrawPen.Color);

반대로 Brush->Color는

Color c = (Brushes.CadetBlue as SolidBrush).Color;

//불투명하게 적용
this.RectangleShape1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
// BackColor 지정
this.RectangleShape1.BackColor = Color.Yellow;


 

 

이와 같은 컨트롤 제작할때 좋은듯..

 

'.Net > Winform' 카테고리의 다른 글

C# 디스플레이 정보 가져오기  (0) 2012.12.06
C# Color->Brush  (0) 2012.11.26
C# 임시폴더, 임시파일 이름 얻기  (0) 2012.11.22
C# DataGridView 특정 Cell 선택 막기  (0) 2012.11.22
C# DataGridView Cell Border 변경  (0) 2012.11.22

//임시폴더 경로가져오기 

string
tempFolderPath = System.IO.Path.GetTempPath();

 

//임시파일 경로가져오기 string tempFile = System.IO.Path.GetTempFileName();

 

'.Net > Winform' 카테고리의 다른 글

C# Color->Brush  (0) 2012.11.26
C# RectangleShape 색 채우기  (0) 2012.11.23
C# DataGridView 특정 Cell 선택 막기  (0) 2012.11.22
C# DataGridView Cell Border 변경  (0) 2012.11.22
C# 선 위에 좌표 존재 여부 판별 (delphi 참조)  (0) 2012.11.05
    class DemandsDataGridView:DataGridView
    {
        DataGridViewCell previousCell;
        bool resetting = false;

        public DemandsDataGridView()
        {
            this.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView_CellPainting);
            this.CellLeave += new DataGridViewCellEventHandler(dataGridView_CellLeave);
            this.SelectionChanged += new EventHandler(dataGridView_SelectionChanged);
        }

        void dataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (this.CurrentCell != null && this.resetting==false)
            {
                if (this.CurrentCell.ColumnIndex == 0 || this.CurrentCell.RowIndex == 0)
                {
                    this.resetting = true;
                    this.CurrentCell.Selected = false;
                    this.CurrentCell = this.previousCell;
                    this.resetting = false;
                }
            }
        }

        void dataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.previousCell = this.CurrentCell;
        }
    }


 

선택이 변경 되었을 때

선택을 막고 싶은 영역으로 들어온다면

Seleted 속성을 false로 변경하고

이전 선택된 Cell로 선택된 Cell을 변경한다.

/* VB
             Private Sub dgvLegends_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles dgvLegends.CellPainting
        'Draw custom cell borders.
        'If current column is DisplayName...
        If dgvLegends.Columns("DisplayName").Index = e.ColumnIndex AndAlso e.RowIndex >= 0 Then
                Dim Brush As New SolidBrush(dgvLegends.ColumnHeadersDefaultCellStyle.BackColor)
                e.Graphics.FillRectangle(Brush, e.CellBounds)
                Brush.Dispose()
                e.Paint(e.CellBounds, DataGridViewPaintParts.All And Not DataGridViewPaintParts.ContentBackground)

                ControlPaint.DrawBorder(e.Graphics, e.CellBounds, dgvLegends.GridColor, 1, ButtonBorderStyle.Solid, dgvLegends.GridColor, 1, ButtonBorderStyle.Solid, dgvLegends.GridColor, 1, ButtonBorderStyle.Solid, dgvLegends.GridColor, 1, ButtonBorderStyle.Solid)

            e.Handled = True
        End If
    End Sub
             */
            if (e.RowIndex == 0 || e.ColumnIndex == 0)
            {
                Brush b = new SolidBrush(Color.Black);
                e.Graphics.FillRectangle(b, e.CellBounds);
                b.Dispose();
                e.Paint(e.CellBounds, DataGridViewPaintParts.All | DataGridViewPaintParts.ContentBackground);
                ControlPaint.DrawBorder(e.Graphics, e.CellBounds, Color.Black, 0, ButtonBorderStyle.Outset,
                    Color.Black, 0, ButtonBorderStyle.Outset, Color.Black, 1,
                    ButtonBorderStyle.Outset, Color.Black, 1, ButtonBorderStyle.Outset);
                e.Handled = true;
            }

e.Paint의 매개변수를 잘살펴봐서 적용 시켜야 한다.

 

한개의 Cell의 Border를 변경하는게 아니라서

Border가 겹쳐서 이상하게 보이는 문제 해결한 코드이다.

 

위의 코드에서는

left와 top의 선의 크기를 0으로 주어서

Border를 겹치지 않게 그리고 있다.

회사에서 delphi소스 보면서 프로젝트 진행하는게 있어서..........

선 위에 마우스 좌표가 존재하는지 판별 하는 알고리즘이다~

식이 궁금한데.........아~~~~~중학 수학부터 책사서 공부해야겠다ㅜㅠ

 

 

 

                               #region 델파이소스 (선 판별)
                                /*
                                function PtOnLine(const P1: TPoint; const P2: TPoint;
                                  const P: TPoint; const Ptol: Integer): Boolean;
                                {-------------------------------------------------------}
                                {  Checks if point P is on line between points P1 & P2  }
                                {-------------------------------------------------------}
                                var
                                  dx,  dy  : Integer;
                                  dx1, dy1 : Integer;
                                  a, b, c  : Integer;
                                begin
                                  Result := False;
                                  dx := P2.X - P1.X;
                                  dy := P2.Y - P1.Y;
                                  dx1 := P.X - P1.X;
                                  dy1 := P.Y - P1.Y;
                                  if (Abs(dx) > 0) and (Abs(dy) < Abs(dx)) then
                                  begin
                                    if (dx*dx1 >= 0) and (Abs(dx1) <= Abs(dx)) then
                                    begin
                                      a := (dy*dx1);
                                      b := (dx*dy1);
                                      c := Abs(dx*Ptol);
                                      if Abs(a-b) <= c then Result := True;
                                    end;
                                  end
                                  else if Abs(dy) > 0 then
                                  begin
                                    if (dy*dy1 >= 0) and (Abs(dy1) <= Abs(dy)) then
                                    begin
                                      a := (dx*dy1);
                                      b := (dy*dx1);
                                      c := Abs(dy*Ptol);
                                      if Abs(a-b) <= c then Result := True;
                                    end;
                                  end;
                                end;*/

                                #endregion
                                Point startP = link.Locations[j];
                                Point endP = link.Locations[j+1];
                                int dx = endP.X - startP.X;
                                int dy = endP.Y - startP.Y;
                                int dx1 = point.X - startP.X;
                                int dy1 = point.Y - startP.Y;
                                int a = 0, b = 0, c = 0;
                                if (Math.Abs(dx) > 0 && Math.Abs(dy) < Math.Abs(dx))
                                {
                                    if (dx * dx1 >= 0 && Math.Abs(dx1) <= Math.Abs(dx))
                                    {
                                        a = (dy * dx1);
                                        b = (dx * dy1);
                                        c = Math.Abs(dx * ptol);
                                        if (Math.Abs(a - b) <= c)
                                        {
                                            iDraw = link;
                                            return iDraw;
                                        }
                                    }
                                }
                                else if (Math.Abs(dy) > 0)
                                {
                                    if (dy * dy1 >= 0 && (Math.Abs(dy1) <= Math.Abs(dy)))
                                    {
                                        a = (dx * dy1);
                                        b = (dy * dx1);
                                        c = Math.Abs(dy * ptol);
                                        if (Math.Abs(a - b) <= c)
                                        {
                                            if (Math.Abs(a - b) <= c)
                                            {
                                                iDraw = link;
                                                return iDraw;
                                            }
                                        }
                                    }
                                }


 

 

        void timer_Tick(object sender, EventArgs e)
        {
            if (this.selectedFigure == null)
                return;

            using (Graphics g = this.panel_drawPaper.CreateGraphics())
            {
                Global global = Global.GetInstance();
                
                Point point = this.PointToScreen(this.selectedFigure.Location);
                point =new Point(point.X-2, point.Y-2);

                Rectangle rect = new Rectangle(point, new Size(global.DrawManager.DrawSize+5, global.DrawManager.DrawSize+5));

                ControlPaint.FillReversibleRectangle(rect, Color.Black);
            }
        }

 

ControlPaint Class의 FillReversibleRectangle 메서드를 이용하면 사각 영역의 해당 색상을 반전시키고,

DrawReversibleFrame 메서드는 사각 영역의 라인의 색상만 반전시킨다.

 

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

        // The following three methods will draw a rectangle and allow 
        // the user to use the mouse to resize the rectangle.  If the 
        // rectangle intersects a control's client rectangle, the 
        // control's color will change.

        bool isDrag = false;
        Rectangle theRectangle = new Rectangle
            (new Point(0, 0), new Size(0, 0));
        Point startPoint;

        private void Form1_MouseDown(object sender,
            System.Windows.Forms.MouseEventArgs e)
        {

            // Set the isDrag variable to true and get the starting point 
            // by using the PointToScreen method to convert form 
            // coordinates to screen coordinates.
            if (e.Button == MouseButtons.Left)
            {
                isDrag = true;
            }

            Control control = (Control)sender;

            // Calculate the startPoint by using the PointToScreen 
            // method.
            startPoint = control.PointToScreen(new Point(e.X, e.Y));
        }

        private void Form1_MouseMove(object sender,
            System.Windows.Forms.MouseEventArgs e)
        {

            // If the mouse is being dragged, 
            // undraw and redraw the rectangle as the mouse moves.
            if (isDrag)

            // Hide the previous rectangle by calling the 
            // DrawReversibleFrame method with the same parameters.
            {
                ControlPaint.DrawReversibleFrame(theRectangle,
                    this.BackColor, FrameStyle.Dashed);

                // Calculate the endpoint and dimensions for the new 
                // rectangle, again using the PointToScreen method.
                Point endPoint = ((Control)sender).PointToScreen(new Point(e.X, e.Y));

                int width = endPoint.X - startPoint.X;
                int height = endPoint.Y - startPoint.Y;
                theRectangle = new Rectangle(startPoint.X,
                    startPoint.Y, width, height);

                // Draw the new rectangle by calling DrawReversibleFrame
                // again.  
                ControlPaint.DrawReversibleFrame(theRectangle,
                    this.BackColor, FrameStyle.Dashed);
            }
        }

        private void Form1_MouseUp(object sender,
            System.Windows.Forms.MouseEventArgs e)
        {

            // If the MouseUp event occurs, the user is not dragging.
            isDrag = false;

            // Draw the rectangle to be evaluated. Set a dashed frame style 
            // using the FrameStyle enumeration.
            ControlPaint.DrawReversibleFrame(theRectangle,
                this.BackColor, FrameStyle.Dashed);

            // Find out which controls intersect the rectangle and 
            // change their color. The method uses the RectangleToScreen  
            // method to convert the Control's client coordinates 
            // to screen coordinates.
            Rectangle controlRectangle;
            for (int i = 0; i < Controls.Count; i++)
            {
                controlRectangle = Controls[i].RectangleToScreen(Controls[i].ClientRectangle);
                if (controlRectangle.IntersectsWith(theRectangle))
                {
                    Controls[i].BackColor = Color.BurlyWood;
                }
            }

            // Reset the rectangle.
            theRectangle = new Rectangle(0, 0, 0, 0);
        }



    }

 

 

 

+ Recent posts