|
|
32.1 How can I programmatically maximize or minimize a form?
|
 |
The Brushes Sample shows you how to use four different brushes in several shapes. Below is a code snippet showing how to use hatched and gradient brushes.
|
Rectangle rect = new Rectangle(35, 190, 100, 100);
|
LinearGradientBrush brush2 = new LinearGradientBrush(rect,
|
Color.DarkOrange, Color.Aquamarine,
|
LinearGradientMode.ForwardDiagonal);
|
g.FillEllipse(brush2, 35, 190, 100, 100);
|
HatchBrush brush1 = new HatchBrush(HatchStyle.DiagonalCross,
|
Color.DarkOrange, Color.Aquamarine);
|
g.FillEllipse(brush1, 35, 190, 100, 100);
|
32.2 How can I display a pop up a confirmation dialog when the user closes the form?
|
 |
You can listen to the Form's Closing event, where you can display a MessageBox as show below:
|
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
|
if (MessageBox.Show("Do you want to close the application?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.No)
|
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
|
If MessageBox.Show("Do you want to close the application?","Close Application",MessageBoxButtons.YesNo) = DialogResult.No Then
|
32.3 How can I center my form?
|
 |
You can set the Form's StartPosition property to CenterScreen to achieve this. |
32.4 How do I prevent users from resizing a form?
|
 |
You can prevent the users from resizing a form by setting the FormBorderStyle to FixedDialog and setting the MaximizeBox property to false.
|
32.5 How do I programmatically set an image as Form's Icon ?
|
 |
You could do so as shown in the code below :
|
Bitmap bmp = imageList1.Images[index] as Bitmap;
|
form1.Icon = Icon.FromHandle(bmp.GetHicon());
|
Dim form1 As Form = New Form()
|
Dim bmp As Bitmap = imageList1.Images(index) as Bitmap
|
form1.Icon = Icon.FromHandle(bmp.GetHicon())
|
32.6 How can I add items to the System Menu of a form.
|
 |
To do this, you can use use iterop to access the GetSystemMenu and AppendMenu Win32 APIs. You also need to override the form's WndProc method to catch and act on the menu message. This idea was posted in the Microsoft newsgroups by Lion Shi. Here are some sample projects. |
32.7 How can I have a form with no title bar, but yet keep the resizing borders?
|
 |
Set your form's Text and ControlBox properties.
|
myForm.ControlBox = false;
|
32.8 How can I tell if a form is closed from the controlbox (system menu) or from a call to Form.Close?
|
 |
One way to do this is to override the form's WndProc method and check for WM_SYSCOMMAND and SC_CLOSE. Looking for WM_CLOSE in the override is not sufficient as WM_CLOSE is seen in both cases. A sample is available for download (C#, VB).
|
public const int SC_CLOSE = 0xF060;
|
public const int WM_SYSCOMMAND = 0x0112;
|
//_closeClick is a bool member of the form initially set false...
|
// It can be tested in the Closing event to see how the closing came about.
|
protected override void WndProc(ref System.Windows.Forms.Message m)
|
if(m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
|
32.9 I have two forms. How can I access a textbox on one form from the other form?
|
 |
One way to do this is to make the TextBox either a public property or a public field. Then you will be able to access it through the instance of its parent form. So, if TextBox1 is a public member of FormA and myFormA is an instance of FormA, then you can use code such as
|
Dim strValue as String = myFormA.TextBox1.Text
|
string strValue = myFormA.TextBox1.Text;
|
anywhere myFormA is known. Here is a VB project illustrating this technique.
|
32.10 How do I create a non-modal top level form that always stays on top of all the app's windows (like the VS.Net find dialog)?
|
 |
Make your main form the "Owner" of the form in question. Refer to Form.Owner in class reference for more information.
|
findReplaceDialog.Owner = this; // Your main form.
|
findReplaceDialog.TopLevel = false;
|
findReplaceDialog.Owner = Me ' Your main form.
|
findReplaceDialog.TopLevel = False
|
32.11 How can I display a form that is 'TopMost' for only my application, but not other applications?
|
 |
The idea is to create the 'bound' table in your dataset, and then add an extra 'unbound' column. The steps are to derive a custom columnstyle that
overrides Paint where you calculate and draw the unbound value. You can also override Edit to prevent the user from selecting your unbound column. Then to get your datagrid to use this special column style, you create a tablestyle and add the column styles to it in the order you want the columns
to appear in the datagrid. Here are code snippets that derive the column and use the derived column. You can download a working sample.
|
// custom column style that is an unbound column
|
public class DataGridUnboundColumn : DataGridTextBoxColumn
|
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
|
//do not allow the unbound cell to become active
|
if(this.MappingName == "UnBound")
|
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
|
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
|
g.FillRectangle(new SolidBrush(Color.White), bounds);
|
//compute & draw the value
|
//string s = string.Format("{0} row", rowNum);
|
// col 0 + 2 chars from col 1
|
DataGrid parent = this.DataGridTableStyle.DataGrid;
|
string s = parent[rowNum, 0].ToString() + ((parent[rowNum, 1].ToString())+ " ").Substring(0,2);
|
Font font = new Font("Arial", 8.25f);
|
g.DrawString(s, font, new SolidBrush(Color.Black), bounds.X, bounds.Y);
|
//code that uses this unbound column
|
private void Form1_Load(object sender, System.EventArgs e)
|
// Set the connection and sql strings
|
// assumes your mdb file is in your root
|
string connString = @"Provider=Microsoft.JET.OLEDB.4.0;data source=C:\northwind.mdb";
|
string sqlString = "SELECT * FROM customers";
|
OleDbDataAdapter dataAdapter = null;
|
OleDbConnection connection = new OleDbConnection(connString);
|
// Create data adapter object
|
dataAdapter = new OleDbDataAdapter(sqlString, connection);
|
// Create a dataset object and fill with data using data adapter's Fill method
|
_dataSet = new DataSet();
|
dataAdapter.Fill(_dataSet, "customers");
|
MessageBox.Show("Problem with DB access-\n\n connection: "
|
+ connString + "\r\n\r\n query: " + sqlString
|
+ "\r\n\r\n\r\n" + ex.ToString());
|
// Create a table style that will hold the new column style
|
// that we set and also tie it to our customer's table from our DB
|
DataGridTableStyle tableStyle = new DataGridTableStyle();
|
tableStyle.MappingName = "customers";
|
// since the dataset has things like field name and number of columns,
|
// we will use those to create new columnstyles for the columns in our DB table
|
int numCols = _dataSet.Tables["customers"].Columns.Count;
|
//add an extra column at the end of our customers table
|
_dataSet.Tables["customers"].Columns.Add("Unbound");
|
DataGridTextBoxColumn aColumnTextColumn ;
|
for(int i = 0; i < numCols; ++i)
|
aColumnTextColumn = new DataGridTextBoxColumn();
|
aColumnTextColumn.HeaderText = _dataSet.Tables["customers"].Columns[i].ColumnName;
|
aColumnTextColumn.MappingName = _dataSet.Tables["customers"].Columns[i].ColumnName;
|
tableStyle.GridColumnStyles.Add(aColumnTextColumn);
|
//display the extra column after column 1.
|
DataGridUnboundColumn unboundColStyle = new DataGridUnboundColumn();
|
unboundColStyle.HeaderText = "UnBound";
|
unboundColStyle.MappingName = "UnBound";
|
tableStyle.GridColumnStyles.Add(unboundColStyle); }
|
// make the dataGrid use our new tablestyle and bind it to our table
|
dataGrid1.TableStyles.Clear();
|
dataGrid1.TableStyles.Add(tableStyle);
|
dataGrid1.DataSource = _dataSet.Tables["customers"];
|
32.12 How do I automatically resize the Form when the screen resolution changes between design-time and runtime?
|
 |
The framework automatically resizes the form if the current Font size during runtime is different from the font size in design-time. It however doesn't auto size when the resolution changes. But it should be easy for you to accomplish. You could derive a custom Form, provide a "ScreenResolutionBase" property that could return the current screen resolution (Screen.PrimarScreen.Bounds will give you this). This value will get serialized in code during design time. Then during runtime in the Form's OnLoad you could check for the current screen resolution and resize the Form appropriately. |
32.13 How can I ensure that my form will always be on the desktop?
|
 |
To set or control the location of the form using desktop coordinates, you can use the SetDeskTopLocation property.
You can do this by setting the child form's TopMost to False and setting its Owner property to the Main Form.
|
this.SetDesktopLocation(1,1);
|
Me.SetDesktopLocation(1,1)
|
32.14 How can I restrict or control the size of my form?
|
 |
You can restrict the size of a form by setting it's MaximumSize and MinimumSize properties. This will help you control the maximum and minimum size the form can be resized to. Also note that WindowState property of the form plays a part in how the form can be resized.
|
//Minimum width = 300, Minimum height= 300
|
this.MinimumSize = new Size(300, 300);
|
//Maximum width = 800, Maximum height= unlimited
|
this.MaximumSize = new Size(800, int.MaxValue);
|
'Minimum width = 300, Minimum height= 300
|
Me.MinimumSize = New Size(300, 300)
|
'Maximum width = 800, Maximum height= unlimited
|
Me.MaximumSize = New Size(800, Integer.MaxValue)
|
32.15 How can I prevent a form from being shown in the taskbar?
|
 |
You need to set the form's ShowInTaskbar property to False to prevent it from being displayed in the Windows taskbar.
|
this.ShowInTaskbar = false;
|
32.16 How do I prevent a user from moving a form at run time?
|
 |
The following code snippet (posted in the Windows Forms FAQ forums) shows how you can prevent a user from moving a form at run time:
|
protected override void WndProc(ref Message m)
|
const int WM_NCLBUTTONDOWN = 161;
|
const int WM_SYSCOMMAND = 274;
|
const int SC_MOVE = 61456;
|
if((m.Msg == WM_SYSCOMMAND) && (m.WParam.ToInt32() == SC_MOVE))
|
if((m.Msg == WM_NCLBUTTONDOWN) && (m.WParam.ToInt32() == HTCAPTION))
|
Protected Overrides Sub WndProc(ByRef m As Message)
|
const Integer WM_NCLBUTTONDOWN = 161
|
const Integer WM_SYSCOMMAND = 274
|
const Integer HTCAPTION = 2
|
const Integer SC_MOVE = 61456
|
If (m.Msg = WM_SYSCOMMAND) &&(m.WParam.ToInt32() = SC_MOVE) Then
|
If (m.Msg = WM_NCLBUTTONDOWN) &&(m.WParam.ToInt32() = HTCAPTION) Then
|
32.17 How can I create a non rectangular form?
|
 |
32.18 How can I make my form cover the whole screen including the TaskBar?
|
 |
The following code snippet demonstrates how you can make your form cover the whole screen including the Windows Taskbar.
|
// Prevent form from being resized.
|
this.FormBorderStyle = FormBorderStyle.FixedSingle;
|
Rectangle formrect = Screen.GetBounds(this);
|
// Set the form's location and size
|
this.Location = formrect.Location;
|
this.Size = formrect.Size;
|
' Prevent form from being resized.
|
Me.FormBorderStyle = FormBorderStyle.FixedSingle
|
Dim formrect As Rectangle = Screen.GetBounds(Me)
|
' Set the form's location and size
|
Me.Location = formrect.Location
|
32.19 How can I move a Borderless form?
|
 |
This code snippet shows how you can move a borderless form.
|
public const int WM_NCLBUTTONDOWN = 0xA1;
|
public const int HTCAPTION = 0x2;
|
[DllImport("User32.dll")]
|
public static extern bool ReleaseCapture();
|
[DllImport("User32.dll")]
|
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
|
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
|
if (e.Button == MouseButtons.Left)
|
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
|
32.20 How do I force a Windows Form application to exit?
|
 |
Your main form is an object of type System.Windows.Forms.Form. Use its Close method to exit the application. If you wish to Exit from a Form's constructor, this will not work. A workaround is to set a boolean flag that you can later check in the Form's Load method to call Close if required.
Another way is to use the Application.Exit() method.
|
32.21 How do I set the default button for a form?
|
 |
Set the form's AcceptButton property. You can do this either through the designer, or through code such as
|
Form1.AcceptButton = button1;
|
32.22 How do I get an HWND for a form?
|
 |
See the Control.Handle property which returns the HWND. Be careful if you pass this handle to some Win32 API as Windows Forms controls do their own handle management so they may recreate the handle which would leave this HWND dangling.
(from sburke_online@microsoft..nospam..com on microsoft.public.dotnet.framework.windowsforms) |
32.23 How can I detect if the user clicks into another window from my modal dialog?
|
 |
Use the Form.Deactivate event:
|
this.Deactivate += new EventHandle(OnDeactivate);
|
private void OnDeactivate(object s, EventArgs e)
|
(from sburke_online@microsoft..nospam..com on microsoft.public.dotnet.framework.windowsforms) |
32.24 How do I create a form with no border?
|
 |
Use the Form.FormBorderStyle property to control a form's border.
|
// Adds a label to the form.
|
Label label1 = new Label();
|
label1.Location = new System.Drawing.Point(80,80);
|
label1.Size = new System.Drawing.Size(132,80);
|
label1.Text = "Start Position Information";
|
this.Controls.Add(label1);
|
// Changes the border to Fixed3D.
|
FormBorderStyle = FormBorderStyle.Fixed3D;
|
// Displays the border information.
|
label1.Text = "The border is " + FormBorderStyle;
|
(From the .NET Framework SDK documentation)
|
32.25 How do I prevent a Form from closing when the user clicks on the close button on the form's system menu?
|
 |
Handle the form's Closing event.
|
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
|
e.Cancel = true; //don't close
|
32.26 How do I display a splash screen type form, one with only client area (no border or titlebar)?
|
 |
public void CreateMyBorderlessWindow()
|
this.FormBorderStyle = FormBorderStyle.None;
|
this.MaximizeBox = false;
|
this.MinimizeBox = false;
|
this.StartPosition = FormStartPosition.CenterScreen;
|
32.27 How do I get the window handle (HWND) of my form or control?
|
 |
Use the Control.Handle property. |
32.28 How can I make sure I don't open a second instance modeless dialog that is already opened from my main form?
|
 |
There are a several of ways to do this. Here are a few:
1) Insert a carriage return-linefeed, "\r\n", between your lines.
|
textBox1.Text = "This is line 1.\r\nThis is line 2";
|
// or textBox1.Text = stringvar1 + "\r\n" + stringvar2;
|
2) Use the Environment.NewLine property. This property is normally set to "\r\n".
|
textBox1.Text = "This is line 1." + Environment.NewLine + "This is line 2";
|
3) Use the Lines property of the TextBox. Make sure you populate your array before you set the property.
|
| |