I was using WinForm’s
CheckedListBox control a few minutes ago and my application was crashing with an out of memory exception. This was happening on the line where new items were being added to the
CheckedListBox. It did not make any sense at all, since I was only adding the second item to the control. Also, I was pretty sure I wasn’t being even close to running out of memory! 😀
By some happy coincidence, I figured out what the problem was. Some of the items I was adding to the list would return
null in their
ToString() method. Turned out that was what was causing the exception. I simply made sure that
ToString() would not return
null values and that solved the issue. .NET can sometimes be stupid 😀
I guess it is advisable to always write the
ToString() methods with a blank string as the starting point (eg.
return "" + this.ID so that it wouldn’t break in case
In WinForms, mouse events are raised regardless of the original source of the mouse. If you click a button with the stylus for instance, you’d still get the MouseClick event. This MSDN page explains how to distinguish between the sources of the event. To make the long story short, you’d have to place an API call to the
GetMessageExtraInfo() function and check the returned value. The following C# code snippet performs the checking:
/// The sources of the input event that is raised and is generally
/// recognized as mouse events.
public enum MouseEventSource
/// Events raised by the mouse
/// Events raised by a stylus
/// Events raised by touching the screen
/// Gets the extra information for the mouse event.
/// <returns>The extra information provided by Windows API</returns>
private static extern uint GetMessageExtraInfo();
/// Determines what input device triggered the mouse event.
/// A result indicating whether the last mouse event was triggered
/// by a touch, pen or the mouse.
public static MouseEventSource GetMouseEventSource()
uint extra = GetMessageExtraInfo();
bool isTouchOrPen = ((extra & 0xFFFFFF00) == 0xFF515700);
bool isTouch = ((extra & 0x00000080) == 0x00000080);
return isTouch ? MouseEventSource.Touch : MouseEventSource.Pen;