Search This Blog

Showing posts with label Windows Forms. Show all posts
Showing posts with label Windows Forms. Show all posts

Monday, April 14, 2014

Drag-and-Drop Operation in Windows Forms

Drag-and-Drop Operation in Windows Forms

To perform drag-and-drop operations within Windows-based applications you must handle a series of events, most notably the DragEnter, DragLeave, and DragDrop events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations.


To Start The Drag Operation

All drag-and-drop operations begin with dragging. The functionality to enable data to be collected when dragging begins is implemented in the DoDragDrop method.
In the following example, the MouseDown event is used to start the drag operation because it is the most intuitive (most drag-and-drop actions begin with the mouse button being depressed). However, remember that any event could be used to initiate a drag-and-drop procedure.
  • In the MouseDown event for the control where the drag will begin, use the DoDragDrop method to set the data to be dragged and the allowed effect dragging will have. For more information, see Data and AllowedEffect.
  • The following example shows how to initiate a drag operation. The control where the drag begins is a Button control, the data being dragged is the string representing the Text property of the Button control, and the allowed effects are either copying or moving.

private void button1_MouseDown(object sender, 
System.Windows.Forms.MouseEventArgs e)
{
   button1.DoDragDrop(button1.Text, DragDropEffects.Copy | 
      DragDropEffects.Move);
}

To perform a drop

Once you have begun dragging data from a location on a Windows Form or control, you will naturally want to drop it somewhere. The cursor will change when it crosses an area of a form or control that is correctly configured for dropping data. Any area within a Windows Form or control can be made to accept dropped data by setting the AllowDrop property and handling the DragEnter and DragDrop events.
  1. Set the AllowDrop property to true.
  2. In the DragEnter event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, Text). The code then sets the effect that will happen when the drop occurs to a value in the DragDropEffects enumeration. 
private void textBox1_DragEnter(object sender, 
System.Windows.Forms.DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.Text)) 
      e.Effect = DragDropEffects.Copy;
   else
      e.Effect = DragDropEffects.None;
}
In the DragDrop event for the control where the drop will occur, use the GetData method to retrieve the data being dragged.
In the example below, a TextBox control is the control being dragged to (where the drop will occur). The code sets the Text property of the TextBox control equal to the data being dragged.
private void textBox1_DragDrop(object sender, 
System.Windows.Forms.DragEventArgs e)
{
   textBox1.Text = e.Data.GetData(DataFormats.Text).ToString();
}

Sunday, March 30, 2014

Formating in DataGridView

To Set Alternating Row Styles for the Windows Forms DataGridView Control

With the DataGridView control, you can specify complete style information for alternating rows. This enables you use style characteristics like foreground color and font, in addition to background color, to differentiate alternating rows.

this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor =
    Color.Beige;
To specify the font used by DataGridView cells
  • Set the Font property of a DataGridViewCellStyle

this.dataGridView1.DefaultCellStyle.Font = new Font("Verdana", 15);

To specify the foreground and background colors of DataGridView cells

Set the ForeColor and BackColor properties of a DataGridViewCellStyle.
this.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;

To specify the foreground and background colors of selected DataGridView cells

  • Set the SelectionForeColor and SelectionBackColor properties of a DataGridViewCellStyle.
this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black;

Use the Row Template to Customize Rows in the Windows Forms DataGridView Control
The DataGridView control uses the row template as a basis for all rows that it adds to the control either through data binding or when you call theDataGridViewRowCollection.Add method without specifying an existing row to use.
The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set anyDataGridViewRow properties, including DefaultCellStyle.
There are some situations where you must use the row template to achieve a particular effect. For example, row height information cannot be stored in a DataGridViewCellStyle, so you must use a row template to change the default height used by all rows. The row template is also useful when you create your own classes derived from DataGridViewRow and you want your custom type used when new rows are added to the control.
  • Set properties on the object retrieved from the DataGridView.RowTemplate property.

DataGridViewRow row = this.dataGridView1.RowTemplate;
row.DefaultCellStyle.BackColor = Color.Bisque;
row.Height = 35;
row.MinimumHeight = 20;


Change the Border and Gridline Styles in the Windows Forms DataGridView Control

To Change the Border and Gridline Styles in the Windows Forms DataGridView Control

With the DataGridView control, you can customize the appearance of the control's border and gridlines to improve the user experience. You can modify the gridline color and the control border style in addition to the border styles for the cells within the control. You can also apply different cell border styles for ordinary cells, row header cells, and column header cells.

To change the gridline color programmatically

  • Set the GridColor property.
this.dataGridView1.GridColor = Color.Blue;

To change the border style of the entire DataGridView control programmatically

  • Set the BorderStyle property to one of the BorderStyle enumeration values.

To change the border styles for DataGridView cells programmatically

  • Set the CellBorderStyle, RowHeadersBorderStyle, and ColumnHeadersBorderStyle properties.
this.dataGridView1.CellBorderStyle =
    DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle =
    DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle =
    DataGridViewHeaderBorderStyle.Single;

Sunday, March 9, 2014

How to save and Restore the Location, Size and Windows State of a .NET Form

Every time we create a new desktop application I find myself having to add some code that will restore the main application window to the position, size and window state at the time of closing. This article presents a simple C# class that may be added to a form to automatically do this.

code of the simple class is here:

public class PersistWindowState : System.ComponentModel.Component
{
    // event info that allows form to persist extra window state data
    public delegate void WindowStateDelegate(object sender, RegistryKey key);
    public event WindowStateDelegate LoadStateEvent;
    public event WindowStateDelegate SaveStateEvent;

    private Form m_parent;
    private string m_regPath;
    private int m_normalLeft;
    private int m_normalTop;
    private int m_normalWidth;
    private int m_normalHeight;
    private FormWindowState m_windowState;
    private bool m_allowSaveMinimized = false;

    public PersistWindowState()
    {
    }

    public Form Parent
    {
        set
        {
            m_parent = value;

            // subscribe to parent form's events
            m_parent.Closing += new System.ComponentModel.CancelEventHandler(OnClosing);
            m_parent.Resize += new System.EventHandler(OnResize);
            m_parent.Move += new System.EventHandler(OnMove);
            m_parent.Load += new System.EventHandler(OnLoad);

            // get initial width and height in case form is never resized
            m_normalWidth = m_parent.Width;
            m_normalHeight = m_parent.Height;
        }
        get
        {
            return m_parent;
        }
    }

    // registry key should be set in parent form's constructor
    public string RegistryPath
    {
        set
        {
            m_regPath = value;        
        }
        get
        {
            return m_regPath;
        }
    }

    public bool AllowSaveMinimized
    {
        set
        {
            m_allowSaveMinimized = value;
        }
    }

    private void OnResize(object sender, System.EventArgs e)
    {
        // save width and height
        if(m_parent.WindowState == FormWindowState.Normal)
        {
            m_normalWidth = m_parent.Width;
            m_normalHeight = m_parent.Height;
        }
    }

    private void OnMove(object sender, System.EventArgs e)
    {
        // save position
        if(m_parent.WindowState == FormWindowState.Normal)
        {
            m_normalLeft = m_parent.Left;
            m_normalTop = m_parent.Top;
        }
        // save state
        m_windowState = m_parent.WindowState;
    }

    private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        // save position, size and state
        RegistryKey key = Registry.CurrentUser.CreateSubKey(m_regPath);
        key.SetValue("Left", m_normalLeft);
        key.SetValue("Top", m_normalTop);
        key.SetValue("Width", m_normalWidth);
        key.SetValue("Height", m_normalHeight);

        // check if we are allowed to save the state as minimized (not normally)
        if(!m_allowSaveMinimized)
        {
            if(m_windowState == FormWindowState.Minimized)
                m_windowState = FormWindowState.Normal;
        }

        key.SetValue("WindowState", (int)m_windowState);
        
        // fire SaveState event
        if(SaveStateEvent != null)
            SaveStateEvent(this, key);
    }

    private void OnLoad(object sender, System.EventArgs e)
    {
        // attempt to read state from registry
        RegistryKey key = Registry.CurrentUser.OpenSubKey(m_regPath);
        if(key != null)
        {
            int left = (int)key.GetValue("Left", m_parent.Left);
            int top = (int)key.GetValue("Top", m_parent.Top);
            int width = (int)key.GetValue("Width", m_parent.Width);
            int height = (int)key.GetValue("Height", m_parent.Height);
            FormWindowState windowState = (FormWindowState)key.GetValue("WindowState", 
                            (int)m_parent.WindowState);

            m_parent.Location = new Point(left, top);
            m_parent.Size = new Size(width, height);
            m_parent.WindowState = windowState;

            // fire LoadState event
            if(LoadStateEvent != null)
                LoadStateEvent(this, key);
        }
    }
}

Saturday, March 8, 2014

How to fill a ComboBox control with the available fonts

you can write this line of code to fill a combo box with
installed system fonts.

comboBox1.Items.AddRange (FontFamily.Families);

Thursday, March 6, 2014

How to move a windows form in .net

To move a windows form in .net 

  • Create a procedure to move the form when it is dragged. Enter code similar to the following to create a new Point object. This will act as a variable when you calculate how to move the form. The isMouseDown field is used to track whether the user is holding the mouse button down. The form should move only when the mouse is held down.
' Visual Basic
Private mouseOffset As Point
Private isMouseDown As Boolean = False
/ C#
/private Point mouseOffset;
private bool isMouseDown = false;
  • Create an event handler for the form's MouseDown event. In the handler, add code that allows a user to click anywhere on the form to drag it. 
Enter code similar to the following to assign coordinates to the mouseOffset variable based on the current position of the mouse pointer. In the code below, notice that the offset position is calculated using system information about the border size (FrameBorderSize.Width) and title bar height(CaptionHeight). These must be taken into account when testing the offset, because some measurements are made with the client area and some are made with screen coordinates. Thus, the offset is equal to the border width plus the caption height plus the offset into the client area of the form.
' Visual Basic
Private Sub Form1_MouseDown(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles MyBase.MouseDown
    Dim xOffset As Integer
    Dim yOffset As Integer

    If e.Button = MouseButtons.Left Then
        xOffset = -e.X - SystemInformation.FrameBorderSize.Width
        yOffset = -e.Y - SystemInformation.CaptionHeight - _
                SystemInformation.FrameBorderSize.Height
        mouseOffset = New Point(xOffset, yOffset)
        isMouseDown = True
    End If
End Sub

// C#
private void Form1_MouseDown(object sender, 
    System.Windows.Forms.MouseEventArgs e)
{
    int xOffset;
    int yOffset;

    if (e.Button == MouseButtons.Left) 
    {
        xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
        yOffset = -e.Y - SystemInformation.CaptionHeight - 
            SystemInformation.FrameBorderSize.Height;
        mouseOffset = new Point(xOffset, yOffset);
        isMouseDown = true;
    }    
}

  • Create an event handler for the form's MouseMove event.
    Enter code similar to the following. When the left mouse button is clicked and the mouse is dragged, the form's Location property is set to the new position.
' Visual Basic
Private Sub Form1_MouseMove(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles MyBase.MouseMove
    If isMouseDown Then
        Dim mousePos As Point = Control.MousePosition
        mousePos.Offset(mouseOffset.X, mouseOffset.Y)
        Location = mousePos
    End If
End Sub

// C#
private void Form1_MouseMove(object sender, 
    System.Windows.Forms.MouseEventArgs e)
{
    if (isMouseDown) 
    {
        Point mousePos = Control.MousePosition;
        mousePos.Offset(mouseOffset.X, mouseOffset.Y);
        Location = mousePos;
    }
}
  • Create an event handler for the form's MouseUp event. Enter code similar to the following.
' Visual Basic
Private Sub Form1_MouseUp(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles MyBase.MouseUp
    ' Changes the isMouseDown field so that the form does
    ' not move unless the user is pressing the left mouse button.
    If e.Button = MouseButtons.Left Then
        isMouseDown = False
    End If
End Sub

// C#
private void Form1_MouseUp(object sender, 
    System.Windows.Forms.MouseEventArgs e)
{
    // Changes the isMouseDown field so that the form does
    // not move unless the user is pressing the left mouse button.
    if (e.Button == MouseButtons.Left) 
    {
        isMouseDown = false;
    }
}

Hope this post will help you.

Creating a shaped form in .net (creating non-rectangular forms)


To create a shaped form
  1. Create a bitmap of a non-rectangular shape of one color with a distinct background of another color. Use any paint program you like. The shape you draw will ultimately be your form, so be sure to draw it large enough to be useful.
  2. In the Properties window:
    • Set the FormBorderStyle property to None.
      This property removes the title bar from the form. (It also removes the functionality that is provided by a title bar, including the ability to close the form and move the form. However, this shortcoming is addressed below in code.)
    • Set the BackgroundImage property of the form to the bitmap file you created earlier. There is no need to add the file to the project system; this will be done automatically when you specify it as the background image.
      This property sets the bitmap image to be the background of the form. (When used in tandem with the TransparencyKey property specified below, this property defines the shape of the form.)
    • Set the TransparencyKey property to the background color of the bitmap file.
      This property tells the application which parts of the form you want to see through.

To write code to close the form
  1. Add code that will allow the user to close the form by invoking its Close method.
    The following example shows how you can add a button that, when clicked, will close the form.
' VB
Private Sub Button1_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles Button1.Click
   Me.Close()
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   this.Close();
}