Check Caps lock on or off




using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class CapsLockControl
{
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;

public static void Main()
{
if (Control.IsKeyLocked(Keys.CapsLock))
{
Console.WriteLine("Caps Lock key is ON. We'll turn it off");
keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
(UIntPtr) 0);
}
else
{
Console.WriteLine("Caps Lock key is OFF");
}
}
}

Virtual Keyboard



public partial class Keyboardcontrol : UserControl
 {
        public Keyboardcontrol()
        {
            InitializeComponent();
        }
        private Boolean shiftindicator = false;
        private Boolean capslockindicator = false;
        private string pvtKeyboardKeyPressed = "";

        private BoW pvtKeyboardType = BoW.Standard;
        public BoW KeyboardType
        {
            get
            {
                return pvtKeyboardType;
            }
            set
            {
                pvtKeyboardType = value;
                if (shiftindicator) HandleShiftClick();
                if (capslockindicator) HandleCapsLock();
                if (pvtKeyboardType == BoW.Standard)
                {
                    pictureBoxKeyboard.Image = KeyboardClassLibrary.Properties.Resources.keyboard_white;
                    pictureBoxCapsLockDown.Image = KeyboardClassLibrary.Properties.Resources.caps_down_white;
                    pictureBoxLeftShiftDown.Image = KeyboardClassLibrary.Properties.Resources.shift_down_white;
                    pictureBoxRightShiftDown.Image = KeyboardClassLibrary.Properties.Resources.shift_down_white;
                }
                else if (pvtKeyboardType==BoW.Alphabetical)
                {
                    pictureBoxKeyboard.Image = KeyboardClassLibrary.Properties.Resources.keyboard_alphabetical;
                    pictureBoxCapsLockDown.Image = KeyboardClassLibrary.Properties.Resources.caps_down_white;
                    pictureBoxLeftShiftDown.Image = KeyboardClassLibrary.Properties.Resources.shift_down_white;
                    pictureBoxRightShiftDown.Image = KeyboardClassLibrary.Properties.Resources.shift_down_white;
                }
                else   //   kids keyboard
                {
                    pictureBoxKeyboard.Image = KeyboardClassLibrary.Properties.Resources.keyboard_kids_lower;
                }
            }
        }

        [Category("Mouse"), Description("Return value of mouseclicked key")]
        public event KeyboardDelegate UserKeyPressed;
        protected virtual void OnUserKeyPressed(KeyboardEventArgs e)
        {
            if (UserKeyPressed != null)
                UserKeyPressed(this, e);
        }
        private void pictureBoxKeyboard_MouseClick(object sender, MouseEventArgs e)
        {
            Single xpos = e.X;
            Single ypos = e.Y;
            xpos = 993 * (xpos / pictureBoxKeyboard.Width);
            ypos = 282 * (ypos / pictureBoxKeyboard.Height);
            if (pvtKeyboardType == BoW.Kids) pvtKeyboardKeyPressed = HandleKidsMouseClick(xpos, ypos);
            else pvtKeyboardKeyPressed = HandleTheMouseClick(xpos, ypos);
            KeyboardEventArgs dea = new KeyboardEventArgs(pvtKeyboardKeyPressed);
            OnUserKeyPressed(dea);
        }
        private void pictureBoxLeftShiftState_MouseClick(object sender, MouseEventArgs e)
        {
            HandleShiftClick();
        }
 
        private void pictureBoxRightShiftState_MouseClick(object sender, MouseEventArgs e)
        {
            HandleShiftClick();
        }
        private void pictureBoxCapsLockState_MouseClick(object sender, MouseEventArgs e)
        {
            HandleCapsLock();
        }

        private string HandleKidsMouseClick(Single x, Single y)
        {
            string Keypressed = null;
            if (y < 73)
            {
                if (x < 79) Keypressed = "a";
                else if (x >= 79 && x < 147) Keypressed = "b";
                else if (x >= 147 && x < 214) Keypressed = "c";
                else if (x >= 214 && x < 281) Keypressed = "d";
                else if (x >= 281 && x < 348) Keypressed = "e";
                else if (x >= 348 && x < 416) Keypressed = "f";
                else if (x >= 416 && x < 491) Keypressed = "g";
                else if (x >= 491 && x < 672) Keypressed = "{BACKSPACE}";
                else if (x >= 672 && x < 764) Keypressed = ".";
                else if (x >= 764 && x < 845) Keypressed = "1";
                else if (x >= 845 && x < 912) Keypressed = "2";
                else if (x >= 912 && x < 989) Keypressed = "3";
            }
            else if (y >= 73 && y < 141)
            {
                if (x < 79) Keypressed = "h";
                else if (x >= 79 && x < 147) Keypressed = "i";
                else if (x >= 147 && x < 214) Keypressed = "j";
                else if (x >= 214 && x < 281) Keypressed = "k";
                else if (x >= 281 && x < 348) Keypressed = "l";
                else if (x >= 348 && x < 416) Keypressed = "m";
                else if (x >= 416 && x < 491) Keypressed = "n";
                else if (x >= 491 && x < 672) HandleCapsLock();
                else if (x >= 672 && x < 764) Keypressed = ",";
                else if (x >= 764 && x < 845) Keypressed = "4";
                else if (x >= 845 && x < 912) Keypressed = "5";
                else if (x >= 912 && x < 989) Keypressed = "6";
            }
            else if (y >= 141 && y < 209)
            {
                if (x < 79) Keypressed = "o";
                else if (x >= 79 && x < 147) Keypressed = "p";
                else if (x >= 147 && x < 214) Keypressed = "q";
                else if (x >= 214 && x < 281) Keypressed = "r";
                else if (x >= 281 && x < 348) Keypressed = "s";
                else if (x >= 348 && x < 416) Keypressed = "t";
                else if (x >= 416 && x < 491) Keypressed = "u";
                else if (x >= 491 && x < 672) Keypressed = "{ENTER}";
                else if (x >= 672 && x < 764) Keypressed = "?";
                else if (x >= 764 && x < 845) Keypressed = "7";
                else if (x >= 845 && x < 912) Keypressed = "8";
                else if (x >= 912 && x < 989) Keypressed = "9";
            }
            else if (y >= 209 && y < 277)
            {
                if (x >= 79 && x < 147) Keypressed = "v";
                else if (x >= 147 && x < 214) Keypressed = "w";
                else if (x >= 214 && x < 281) Keypressed = "x";
                else if (x >= 281 && x < 348) Keypressed = "y";
                else if (x >= 348 && x < 416) Keypressed = "z";
                else if (x >= 491 && x < 672) Keypressed = " ";
                else if (x >= 672 && x < 764) Keypressed = "!";
                else if (x >= 764 && x < 845) Keypressed = "{+}";
                else if (x >= 845 && x < 912) Keypressed = "0";
                else if (x >= 912 && x < 989) Keypressed = "-";
            }
            if (capslockindicator && x < 491) return "+" + Keypressed;
            else return Keypressed;
        }
        private string HandleTheMouseClick(Single x, Single y)
        {
            string Keypressed = null;
            if (x >= 4 && x < 815 && y >= 3 && y < 277)         //  keyboard section
            {
                if (y < 58)
                {
                    if (x >= 4 && x < 59) Keypressed = HandleShiftableKey("`");
                    else if (x >= 67 && x < 112) Keypressed = HandleShiftableKey("1");
                    else if (x >= 112 && x < 165) Keypressed = HandleShiftableKey("2");
                    else if (x >= 165 && x < 220) Keypressed = HandleShiftableKey("3");
                    else if (x >= 220 && x < 275) Keypressed = HandleShiftableKey("4");
                    else if (x >= 275 && x < 328) Keypressed = HandleShiftableKey("5");
                    else if (x >= 328 && x < 380) Keypressed = HandleShiftableKey("6");
                    else if (x >= 380 && x < 435) Keypressed = HandleShiftableKey("7");
                    else if (x >= 435 && x < 490) Keypressed = HandleShiftableKey("8");
                    else if (x >= 490 && x < 545) Keypressed = HandleShiftableKey("9");
                    else if (x >= 545 && x < 600) Keypressed = HandleShiftableKey("0");
                    else if (x >= 600 && x < 655) Keypressed = HandleShiftableKey("-");
                    else if (x >= 655 && x < 705) Keypressed = HandleShiftableKey("=");
                    else if (x >= 705 && x < 815) Keypressed = "{BACKSPACE}";
                    else Keypressed = null;
                }
                else if (y >= 58 && y < 114)
                {
                    if (x >= 85 && x < 140) Keypressed = HandleShiftableCaplockableKey("q");
                    else if (x >= 140 && x < 193) Keypressed = HandleShiftableCaplockableKey("w");
                    else if (x >= 193 && x < 247) Keypressed = HandleShiftableCaplockableKey("e");
                    else if (x >= 247 && x < 300) Keypressed = HandleShiftableCaplockableKey("r");
                    else if (x >= 300 && x < 355) Keypressed = HandleShiftableCaplockableKey("t");
                    else if (x >= 355 && x < 409) Keypressed = HandleShiftableCaplockableKey("y");
                    else if (x >= 409 && x < 463) Keypressed = HandleShiftableCaplockableKey("u");
                    else if (x >= 463 && x < 517) Keypressed = HandleShiftableCaplockableKey("i");
                    else if (x >= 517 && x < 571) Keypressed = HandleShiftableCaplockableKey("o");
                    else if (x >= 571 && x < 625) Keypressed = HandleShiftableCaplockableKey("p");
                    else if (x >= 625 && x < 680) Keypressed = HandleShiftableKey("{[}");
                    else if (x >= 680 && x < 733) Keypressed = HandleShiftableKey("{]}");
                    else Keypressed = null;
                }
                else if (y >= 114 && y < 168)
                {
                    if (x >= 4 && x < 113) HandleCapsLock();
                    else if (x >= 113 && x < 167) Keypressed = HandleShiftableCaplockableKey("a");
                    else if (x >= 167 && x < 221) Keypressed = HandleShiftableCaplockableKey("s");
                    else if (x >= 221 && x < 275) Keypressed = HandleShiftableCaplockableKey("d");
                    else if (x >= 275 && x < 330) Keypressed = HandleShiftableCaplockableKey("f");
                    else if (x >= 330 && x < 383) Keypressed = HandleShiftableCaplockableKey("g");
                    else if (x >= 383 && x < 437) Keypressed = HandleShiftableCaplockableKey("h");
                    else if (x >= 437 && x < 491) Keypressed = HandleShiftableCaplockableKey("j");
                    else if (x >= 491 && x < 545) Keypressed = HandleShiftableCaplockableKey("k");
                    else if (x >= 545 && x < 599) Keypressed = HandleShiftableCaplockableKey("l");
                    else if (x >= 599 && x < 653) Keypressed = HandleShiftableKey(";");
                    else if (x >= 653 && x < 706) Keypressed = HandleShiftableKey("'");
                    else if (x >= 706 && x < 815) Keypressed = "{ENTER}";
                    else Keypressed = null;
                }
                else if (y >= 168 && y < 221)
                {
                    if (x >= 4 && x < 140) HandleShiftClick();
                    else if (x >= 140 && x < 194) Keypressed = HandleShiftableCaplockableKey("z");
                    else if (x >= 194 && x < 248) Keypressed = HandleShiftableCaplockableKey("x");
                    else if (x >= 248 && x < 302) Keypressed = HandleShiftableCaplockableKey("c");
                    else if (x >= 302 && x < 356) Keypressed = HandleShiftableCaplockableKey("v");
                    else if (x >= 356 && x < 410) Keypressed = HandleShiftableCaplockableKey("b");
                    else if (x >= 410 && x < 464) Keypressed = HandleShiftableCaplockableKey("n");
                    else if (x >= 464 && x < 518) Keypressed = HandleShiftableCaplockableKey("m");
                    else if (x >= 518 && x < 572) Keypressed = HandleShiftableKey(",");
                    else if (x >= 572 && x < 626) Keypressed = HandleShiftableKey(".");
                    else if (x >= 626 && x < 680) Keypressed = HandleShiftableKey("/");
                    else if (x >= 680 && x < 815) HandleShiftClick();
                    else Keypressed = null;
                }
                else if (y >= 221 && y < 277)
                {
                    if (x >= 218 && x < 597) Keypressed = " ";
                    else Keypressed = null;
                }
            else if (x >= 827 && x < 989 && y >= 27 && y < 193)   //  cursor keys
            {
                if (y < 83)
                {
                    if (x < 880) Keypressed = "{INSERT}";
                    else if (x >= 880 && x < 934) Keypressed = "{UP}";
                    else if (x >= 934) Keypressed = HandleShiftableKey("{HOME}");
                    else Keypressed = null;
                }
                else if (y >= 83 && y < 137)
                {
                    if (x < 880) Keypressed = "{LEFT}";
                    else if (x >= 934) Keypressed = "{RIGHT}";
                    else Keypressed = null;
                }
                else if (y >= 137)
                {
                    if (x < 880) Keypressed = "{DELETE}";
                    else if (x >= 880 && x < 934) Keypressed = "{DOWN}";
                    else if (x >= 934) Keypressed = HandleShiftableKey("{END}");
                    else Keypressed = null;
                }
                else Keypressed = null;
            }
            if (Keypressed != null)
            {
                if (shiftindicator) HandleShiftClick();
                return Keypressed;
            }
            else
            {
                return null;
            }
        }
        private string HandleShiftableKey(string theKey)
        {
            if (shiftindicator)
            {
                return "+" + theKey;
            }
            else
            {
                return theKey;
            }
        }
        private string HandleShiftableCaplockableKey(string theKey)
        {
            if (pvtKeyboardType != BoW.Standard)
            {
                switch (theKey)
                {
                    case ("q"):
                        theKey = "a";
                        break;
                    case ("w"):
                        theKey = "b";
                        break;
                    case ("e"):
                        theKey = "c";
                        break;
                    case ("r"):
                        theKey = "d";
                        break;
                    case ("t"):
                        theKey = "e";
                        break;
                    case ("y"):
                        theKey = "f";
                        break;
                    case ("u"):
                        theKey = "g";
                        break;
                    case ("i"):
                        theKey = "h";
                        break;
                    case ("o"):
                        theKey = "i";
                        break;
                    case ("p"):
                        theKey = "j";
                        break;
                    case ("a"):
                        theKey = "k";
                        break;
                    case ("s"):
                        theKey = "l";
                        break;
                    case ("d"):
                        theKey = "m";
                        break;
                    case ("f"):
                        theKey = "n";
                        break;
                    case ("g"):
                        theKey = "o";
                        break;
                    case ("h"):
                        theKey = "p";
                        break;
                    case ("j"):
                        theKey = "q";
                        break;
                    case ("k"):
                        theKey = "r";
                        break;
                    case ("l"):
                        theKey = "s";
                        break;
                    case ("z"):
                        theKey = "t";
                        break;
                    case ("x"):
                        theKey = "u";
                        break;
                    case ("c"):
                        theKey = "v";
                        break;
                    case ("v"):
                        theKey = "w";
                        break;
                    case ("b"):
                        theKey = "x";
                        break;
                    case ("n"):
                        theKey = "y";
                        break;
                    case ("m"):
                        theKey = "z";
                        break;
                }
            }
            if (capslockindicator)
            {
                return "+" + theKey;
            }
            else if (shiftindicator)
            {
                return "+" + theKey;
            }
            else
            {
                return theKey;
            }
        }
        private void HandleShiftClick()
        {
            if (shiftindicator)
            {
                shiftindicator = false;
                pictureBoxLeftShiftDown.Visible = false;
                pictureBoxRightShiftDown.Visible = false;
            }
            else
            {
                shiftindicator = true;
                pictureBoxLeftShiftDown.Visible = true;
                pictureBoxRightShiftDown.Visible = true;
            }
        }
        private void HandleCapsLock()
        {
            if (capslockindicator)
            {
                capslockindicator = false;
                pictureBoxCapsLockDown.Visible = false;
                if (pvtKeyboardType == BoW.Kids) pictureBoxKeyboard.Image = KeyboardClassLibrary.Properties.Resources.keyboard_kids_lower;
            }
            else
            {
                capslockindicator = true;
                if (pvtKeyboardType == BoW.Kids) pictureBoxKeyboard.Image = KeyboardClassLibrary.Properties.Resources.keyboard_kids_upper;
                else pictureBoxCapsLockDown.Visible = true;
            }
        }
        private void pictureBoxKeyboard_SizeChanged(object sender, EventArgs e)
        {
            // position the capslock and shift down overlays
            pictureBoxCapsLockDown.Left = Convert.ToInt16(pictureBoxKeyboard.Width * 5 / 993);
            pictureBoxCapsLockDown.Top = Convert.ToInt16(pictureBoxKeyboard.Height * 115 / 282);
            pictureBoxLeftShiftDown.Left = Convert.ToInt16(pictureBoxKeyboard.Width * 5 / 993);
            pictureBoxLeftShiftDown.Top = Convert.ToInt16(pictureBoxKeyboard.Height * 169 / 282);
            pictureBoxRightShiftDown.Left = Convert.ToInt16(pictureBoxKeyboard.Width * 681 / 993);
            pictureBoxRightShiftDown.Top = pictureBoxLeftShiftDown.Top;
            // size the capslock and shift down overlays
            pictureBoxCapsLockDown.Width = Convert.ToInt16(pictureBoxKeyboard.Width * 110 / 993);
            pictureBoxCapsLockDown.Height = Convert.ToInt16(pictureBoxKeyboard.Height * 55 / 282);
            pictureBoxLeftShiftDown.Width = Convert.ToInt16(pictureBoxKeyboard.Width * 136 / 993);
            pictureBoxLeftShiftDown.Height = Convert.ToInt16(pictureBoxKeyboard.Height * 55 / 282);
            pictureBoxRightShiftDown.Width = Convert.ToInt16(pictureBoxKeyboard.Width * 135 / 993);
            pictureBoxRightShiftDown.Height = pictureBoxLeftShiftDown.Height;
        }
    }
    public delegate void KeyboardDelegate(object sender, KeyboardEventArgs e);
    public class KeyboardEventArgs : EventArgs
    {
       private readonly string pvtKeyboardKeyPressed;

        public KeyboardEventArgs(string KeyboardKeyPressed)
        {
            this.pvtKeyboardKeyPressed = KeyboardKeyPressed;
        }
        public string KeyboardKeyPressed
        {
            get
            {
                return pvtKeyboardKeyPressed;
            }
        }
    }

    [Category("Keyboard Type"),Description("Type of keyboard to use")]
    public enum BoW { Standard, Alphabetical, Kids };

Read Text File

Get All Files from Directory



// Read the file as one string.
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
// Display the file contents to the console.
Console.WriteLine("Contents of writeText.txt = {0}", text);

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");            
Console.WriteLine("Contents of writeLines2.txt =:");
 foreach (string line in lines)
 {
     Console.WriteLine("\t" + line);
 }


Console.ReadKey();

Get System Drives



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;  
namespace DirList
{ 
   class Test
   {
        public static void Main()
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives(); 
            foreach (DriveInfo dirInfo in allDrives)
            {
                Console.WriteLine("Drive {0}", dirInfo.Name);
                Console.WriteLine("File type: {0}", dirInfo.DriveType);
                if (dirInfo.IsReady == true)
                {
                    Console.WriteLine("Volume label: {0}", dirInfo.VolumeLabel);
                    Console.WriteLine("File system: {0}", dirInfo.DriveFormat);
                    Console.WriteLine("Available space:{0, 15} bytes", dirInfo.AvailableFreeSpace); 
                    Console.WriteLine("Total available space: {0, 15} bytes", dirInfo.TotalFreeSpace); 
                    Console.WriteLine("Total size:{0, 15} bytes ",dirInfo.TotalSize);
                    Console.WriteLine("\n"); 
              }
          }
          Console.Read();
      }
   } 
}

DataGridView Printer



using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;

namespace Mesoft.Control
{
    public class DataGridViewPrinter
    {
        private DataGridView TheDataGridView; // The DataGridView Control which will be printed
        private PrintDocument ThePrintDocument; // The PrintDocument to be used for printing
        private bool IsCenterOnPage; // Determine if the report will be printed in the Top-Center of the page
        private bool IsWithTitle; // Determine if the page contain title text
        private string TheTitleText; // The title text to be printed in each page (if IsWithTitle is set to true)
        private Font TheTitleFont; // The font to be used with the title text (if IsWithTitle is set to true)
        private Color TheTitleColor; // The color to be used with the title text (if IsWithTitle is set to true)
        private bool IsWithPaging; // Determine if paging is used
        static int CurrentRow; // A static parameter that keep track on which Row (in the DataGridView control) that should be printed
        static int PageNumber;
        private int PageWidth;
        private int PageHeight;
        private int LeftMargin;
        private int TopMargin;
        private int RightMargin;
        private int BottomMargin;
        private float CurrentY; // A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate
        private float RowHeaderHeight;
        private List RowsHeight;
        private List ColumnsWidth;
        private float TheDataGridViewWidth;
        // Maintain a generic list to hold start/stop points for the column printing
        // This will be used for wrapping in situations where the DataGridView will not fit on a single page
        private List mColumnPoints;
        private List mColumnPointsWidth;
        private int mColumnPoint;
        // The class constructor
        public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument, bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont, Color aTitleColor, bool WithPaging)
        {
            TheDataGridView = aDataGridView;
            ThePrintDocument = aPrintDocument;
            IsCenterOnPage = CenterOnPage;
            IsWithTitle = WithTitle;
            TheTitleText = aTitleText;
            TheTitleFont = aTitleFont;
           TheTitleColor = aTitleColor;
            IsWithPaging = WithPaging;
            PageNumber = 0;
            RowsHeight = new List();
            ColumnsWidth = new List();
            mColumnPoints = new List();
            mColumnPointsWidth = new List();
            // Claculating the PageWidth and the PageHeight
            if (!ThePrintDocument.DefaultPageSettings.Landscape)
            {
                PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
                PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
            }
            else
            {
                PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
                PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
            }
            // Claculating the page margins
            LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
            TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
            RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
            BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;
            // First, the current row to be printed is the first row in the DataGridView control
            CurrentRow = 0;
        }
        // The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width
        private void Calculate(Graphics g)
        {
            if (PageNumber == 0) // Just calculate once
            {
                SizeF tmpSize = new SizeF();
                Font tmpFont;
                float tmpWidth;
                TheDataGridViewWidth = 0;
                for (int i = 0; i < TheDataGridView.Columns.Count; i++)
                {
                    tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
                    if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
                        tmpFont = TheDataGridView.DefaultCellStyle.Font;
                    tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont);
                    tmpWidth = tmpSize.Width;
                    RowHeaderHeight = tmpSize.Height;
                    for (int j = 0; j < TheDataGridView.Rows.Count; j++)
                    {
                        tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font;
                        if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                           tmpFont = TheDataGridView.DefaultCellStyle.Font;
                        tmpSize = g.MeasureString("Anything", tmpFont);
                        RowsHeight.Add(tmpSize.Height);
                        tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                        if (tmpSize.Width > tmpWidth)
                            tmpWidth = tmpSize.Width;
                    }
                    if (TheDataGridView.Columns[i].Visible)
                        TheDataGridViewWidth += tmpWidth;
                    ColumnsWidth.Add(tmpWidth);
                }
                // Define the start/stop column points based on the page width and the DataGridView Width
                // We will use this to determine the columns which are drawn on each page and how wrapping will be handled
                // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine
                int k;
                int mStartPoint = 0;
                for (k = 0; k < TheDataGridView.Columns.Count; k++)
                    if (TheDataGridView.Columns[k].Visible)
                    {
                        mStartPoint = k;
                        break;
                    }
                int mEndPoint = TheDataGridView.Columns.Count;
                for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--)
                    if (TheDataGridView.Columns[k].Visible)
                    {
                        mEndPoint = k + 1;
                        break;
                    }
                float mTempWidth = TheDataGridViewWidth;
                float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin;
                // We only care about handling where the total datagridview width is bigger then the print area
                if (TheDataGridViewWidth > mTempPrintArea)
                {
                    mTempWidth = 0.0F;
                    for (k = 0; k < TheDataGridView.Columns.Count; k++)
                    {
                        if (TheDataGridView.Columns[k].Visible)
                        {
                           mTempWidth += ColumnsWidth[k];
                            // If the width is bigger than the page area, then define a new column print range
                            if (mTempWidth > mTempPrintArea)
                            {
                               mTempWidth -= ColumnsWidth[k];
                                mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                                mColumnPointsWidth.Add(mTempWidth);
                                mStartPoint = k;
                                mTempWidth = ColumnsWidth[k];
                            }
                        }
                        // Our end point is actually one index above the current index
                        mEndPoint = k + 1;
                    }
                }
                // Add the last set of columns
                mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                mColumnPointsWidth.Add(mTempWidth);
                mColumnPoint = 0;
            }
        }
        // The funtion that print the title, page number, and the header row
        private void DrawHeader(Graphics g)
        {
            CurrentY = (float)TopMargin;
            // Printing the page number (if isWithPaging is set to true)
            if (IsWithPaging)
            {
                PageNumber++;
                string PageString = "Page " + PageNumber.ToString();
                StringFormat PageStringFormat = new StringFormat();
                PageStringFormat.Trimming = StringTrimming.Word;
                PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                PageStringFormat.Alignment = StringAlignment.Far;
                Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
                RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height);
                g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
                CurrentY += g.MeasureString(PageString, PageStringFont).Height;
            }
            // Printing the title (if IsWithTitle is set to true)
            if (IsWithTitle)
            {
                StringFormat TitleFormat = new StringFormat();
                TitleFormat.Trimming = StringTrimming.Word;
                TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                if (IsCenterOnPage)
                    TitleFormat.Alignment = StringAlignment.Center;
                else
                    TitleFormat.Alignment = StringAlignment.Near;
                RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height);
                g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat);
                CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
            }
            // Calculating the starting x coordinate that the printing process will start from
            float CurrentX = (float)LeftMargin;
            if (IsCenterOnPage)
                CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
            // Setting the HeaderFore style
            Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
            if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style
                HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
            SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
            // Setting the HeaderBack style
            Color HeaderBackColor = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
            if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style
                HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
            SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
            // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
            Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
            // Setting the HeaderFont style
            Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
            if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
                HeaderFont = TheDataGridView.DefaultCellStyle.Font;
            // Calculating and drawing the HeaderBounds
            RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
            g.FillRectangle(HeaderBackBrush, HeaderBounds);
            // Setting the format that will be used to print each cell of the header row
            StringFormat CellFormat = new StringFormat();
            CellFormat.Trimming = StringTrimming.Word;
            CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            // Printing each visible cell of the header row
            RectangleF CellBounds;
            float ColumnWidth;
            for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
            {
                if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration
                ColumnWidth = ColumnsWidth[i];
                // Check the CurrentCell alignment and apply it to the CellFormat
                if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                    CellFormat.Alignment = StringAlignment.Far;
                else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                    CellFormat.Alignment = StringAlignment.Center;
                else
                    CellFormat.Alignment = StringAlignment.Near;
                CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
                // Printing the cell text
                g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);
                // Drawing the cell bounds
                if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None
                    g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
                CurrentX += ColumnWidth;
            }
            CurrentY += RowHeaderHeight;
        }
        // The function that print a bunch of rows that fit in one page
        // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required
        // When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required
        private bool DrawRows(Graphics g)
        {
            // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
            Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
            // The style paramters that will be used to print each cell
            Font RowFont;
            Color RowForeColor;
            Color RowBackColor;
            SolidBrush RowForeBrush;
            SolidBrush RowBackBrush;
            SolidBrush RowAlternatingBackBrush;
            // Setting the format that will be used to print each cell
            StringFormat CellFormat = new StringFormat();
            CellFormat.Trimming = StringTrimming.Word;
            CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
            // Printing each visible cell
            RectangleF RowBounds;
            float CurrentX;
            float ColumnWidth;
            while (CurrentRow < TheDataGridView.Rows.Count)
            {
                if (TheDataGridView.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible
                {
                    // Setting the row font style
                    RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font;
                    if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                        RowFont = TheDataGridView.DefaultCellStyle.Font;
                    // Setting the RowFore style
                    RowForeColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor;
                    if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control
                        RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
                    RowForeBrush = new SolidBrush(RowForeColor); 
                    // Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles
                    RowBackColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor;
                    if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control
                    {
                        RowBackBrush = new SolidBrush(TheDataGridView.DefaultCellStyle.BackColor);
                        RowAlternatingBackBrush = new SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                    }
                    else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles
                    {
                        RowBackBrush = new SolidBrush(RowBackColor);
                        RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                    }
                    // Calculating the starting x coordinate that the printing process will start from
                    CurrentX = (float)LeftMargin;
                    if (IsCenterOnPage)
                        CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
                    // Calculating the entire CurrentRow bounds
                    RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]);
                    // Filling the back of the CurrentRow
                    if (CurrentRow % 2 == 0)
                        g.FillRectangle(RowBackBrush, RowBounds);
                    else
                        g.FillRectangle(RowAlternatingBackBrush, RowBounds);
                    // Printing each visible cell of the CurrentRow
                    for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
                    {
                        if (!TheDataGridView.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration
                        // Check the CurrentCell alignment and apply it to the CellFormat
                        if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
                            CellFormat.Alignment = StringAlignment.Far;
                        else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
                            CellFormat.Alignment = StringAlignment.Center;
                        else
                            CellFormat.Alignment = StringAlignment.Near;
                        ColumnWidth = ColumnsWidth[CurrentCell];
                        RectangleF CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);
                        // Printing the cell text
                        g.DrawString(TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
                        // Drawing the cell bounds
                        if (TheDataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None
                            g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);
                        CurrentX += ColumnWidth;
                    }
                    CurrentY += RowsHeight[CurrentRow];
                    // Checking if the CurrentY is exceeds the page boundries
                    // If so then exit the function and returning true meaning another PagePrint action is required
                    if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))
                    {
                        CurrentRow++;
                        return true;
                    }
                }
                CurrentRow++;
            }
            CurrentRow = 0;
            mColumnPoint++; // Continue to print the next group of columns
            if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed
            {
                mColumnPoint = 0;
                return false;
            }
            else
                return true;
        }
        // The method that calls all other functions
        public bool DrawDataGridView(Graphics g)
        {
            try
            {
                Calculate(g);
                DrawHeader(g);
                bool bContinue = DrawRows(g);
                return bContinue;
            }
            catch (Exception ex)
            {
                General.ErrorMessage(ex.Message);
                return false;
            }
        }
        //Customize
        private void DrawHeaderNew(Graphics g)
        {
            //CurrentY = (float)PageHeight;
            CurrentY = (float)(PageHeight - BottomMargin);
            // Printing the page number (if isWithPaging is set to true)
            if (IsWithPaging)
            {
                PageNumber++;
                //string PageString = "Page " + PageNumber.ToString();
                string PageString = "©Callahan & Associates, Inc (800-446-7453)";
                StringFormat PageStringFormat = new StringFormat();
                PageStringFormat.Trimming = StringTrimming.Word;
                PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                PageStringFormat.Alignment = StringAlignment.Far;
                Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
                RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height);
                g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
                CurrentY = (float)TopMargin;
                //CurrentY += g.MeasureString(PageString, PageStringFont).Height;
            }
            // Printing the title (if IsWithTitle is set to true)
            if (IsWithTitle)
            {
                StringFormat TitleFormat = new StringFormat();
                TitleFormat.Trimming = StringTrimming.Word;
                TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                if (IsCenterOnPage)
                    TitleFormat.Alignment = StringAlignment.Center;
                else
                    TitleFormat.Alignment = StringAlignment.Near;
                RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height);
                g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat);
                CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
            }
            // Calculating the starting x coordinate that the printing process will start from
            float CurrentX = (float)LeftMargin;
            if (IsCenterOnPage)
                CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
            // Setting the HeaderFore style
            Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
            if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style
                HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
            SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
            // Setting the HeaderBack style
            Color HeaderBackColor = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
            if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style
                HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
            SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
            // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
            Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
            // Setting the HeaderFont style
            Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
            if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
                HeaderFont = TheDataGridView.DefaultCellStyle.Font;
            // Calculating and drawing the HeaderBounds
            RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
            g.FillRectangle(HeaderBackBrush, HeaderBounds);
            // Setting the format that will be used to print each cell of the header row
            StringFormat CellFormat = new StringFormat();
            CellFormat.Trimming = StringTrimming.Word;
            CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            // Printing each visible cell of the header row
            RectangleF CellBounds;
            float ColumnWidth;
            for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
            {
                if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration
                ColumnWidth = ColumnsWidth[i];
                // Check the CurrentCell alignment and apply it to the CellFormat
                if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                    CellFormat.Alignment = StringAlignment.Far;
                else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                    CellFormat.Alignment = StringAlignment.Center;
                else
                    CellFormat.Alignment = StringAlignment.Near;
                CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
                // Printing the cell text
                g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);
                // Drawing the cell bounds
                if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None
                    g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
                CurrentX += ColumnWidth;
            }
            CurrentY += RowHeaderHeight;
        }
        public bool DrawDataGridViewNew(Graphics g)
        {
            try
            {
                Calculate(g);
                DrawHeaderNew(g);
                bool bContinue = DrawRows(g);
                return bContinue;
            }
            catch (Exception ex)
            {
                General.ErrorMessage(ex.Message);
                return false;
            }
        }
    }
}
/**************************************************************
* IMPLEMENT THIS CODE AS PER BELOW
***************************************************************/
//Setting For The Printer
private bool fnc_SetupThePrinting()
{
    try
    {
        PrintDialog MyPrintDialog = new PrintDialog();
        MyPrintDialog.AllowCurrentPage = false;
        MyPrintDialog.AllowPrintToFile = false;
        MyPrintDialog.AllowSelection = false;
        MyPrintDialog.AllowSomePages = false;
        MyPrintDialog.PrintToFile = false;
        MyPrintDialog.ShowHelp = false;
        MyPrintDialog.ShowNetwork = false;
        if (MyPrintDialog.ShowDialog() != DialogResult.OK)
        return false;
        MyPrintDocument.DocumentName = this.Text;
        MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;
        MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
        MyPrintDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);
        MyDataGridViewPrinter = new DataGridViewPrinter(dgvView, MyPrintDocument, false, true, this.Text, new Font("Tahoma", 12, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
        return true;
    }
    catch (Exception ex)
    {
        objGL.pro_ErrorMessage(ex);
        return false;
    }
}
//Print Button Click event
private void btnPrint_Click(object sender, EventArgs e)
{
    try
    {
    // For Print Preview
    if (fnc_SetupThePrinting())
    {
       PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
        MyPrintPreviewDialog.Document = MyPrintDocument;
        MyPrintPreviewDialog.ShowDialog();
    }
    }
    catch (Exception ex)
    {
        objGL.pro_ErrorMessage(ex);
    }