Tuesday 1 May 2012

TextBox Colored Border

How to change Textbox border color when user enters in to it
Step 1:
Open visual studio ->New project-> Window form application
Add textbox from toolbox to the form and write the  following code

Form1.cs


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

namespace textboxcolorborder
{
    public partial class Form1 : Form
    {
        bool focus = false;

        public Form1()
        {
            InitializeComponent();
           

        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            focus = true;
            this.Refresh();

        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            focus = false;
            this.Refresh();

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (focus)
            {
                textBox1.BorderStyle = BorderStyle.None;
                Pen p = new Pen(Color.Red);
                Graphics g = e.Graphics;
                int variance = 3;
                g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height + variance));
            }
            else
            {
                textBox1.BorderStyle = BorderStyle.FixedSingle;
            }

        }

       
    }
}

 
Demo:

 

No comments:

Post a Comment