Category Archives: C#

Notes on C# / .NET

Scrollable panels and the Paint event.

When a panel has scrollbars ‘default’ drawing on the DC does not  work correctly when the upper-left is not at 0,0.  Graphics functions draw on the current client area, even when scrolled the upper-left posotion of the client area is still at 0,0.

Use the function TranslateTransform to offset the coordinates.

Example

private void dc_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.TranslateTransform(dc.AutoScrollPosition.X, dc.AutoScrollPosition.Y);
   //0,0 is now relative to the total scrollable area, not the visible part (client area).
}

Notes:

Although this will work great for simple drawing and unnecessary drawing is limited (being clipped ), some form of optimization would speed things up considerably.

To setup a larger DC size as visible set the properties AutoScroll to  true and the property AutoScrollMinSize to a size larger then the visible area.

Lastest update in May 2011, inital post in May 2011

Mousewheel handling somewhat different than expected

Getting the mouse wheel works somewhat different than expected.

  1. The event can not be added from the designer so it needs to be added manually. MouseWheel += … This is easy since the implementation is generated automatically (Two TAB presses)
  2. The mouse wheel messages are send to the control which has the current focus. If the control does not support receiving focus use the parent to add the event handler to. For example, in case of a Panel add the event handler to the Form.
Lastest update in May 2011, inital post in May 2011

Disable a toolbar or ToolStripPanel

Individual toolbars / toolstrips can be disabled by using the enabled property.

When in a ToolStrip in inside a ToolStripContainer the entire panel (and the hosted toolstrips) can be disabled all at once.

For example
toolStripContainer1.TopToolStripPanel.Enabled = false;
toolStripContainer1.BottomToolStripPanel.Enabled = false;
toolStripContainer1.LeftToolStripPanel.Enabled = false;
toolStripContainer1.RightToolStripPanel.Enabled = false;

Note:
Do not disable the toolStripContainer1 since it will also disable the hosted panel in the center.

Lastest update in May 2011, inital post in May 2011

Enabling keyboard input on Forms

By default forms do not get keyboard input.

To allow keyboard input set the forms  KeyPreview property to true.

This will enable the firing of the  KeyDown and  KeyUp events.

Lastest update in May 2011, inital post in May 2011