MouseHover event in Windows Forms .Net – Generating it repeatedly

MouseHover Event

When mouse is stationary for some time over a Windows Forms control, Mouse Hover event is generated. This event is generated only once during mouse’s stay and movement over a control. If mouse leaves and re-enters the control, system again starts tracking for Mouse Hover and will generate the event accordingly.

A common use of Mouse Hover event is to display tool tip.

Following code attaches MouseHover handler to a control.

myControl.MouseHover += myControl_MouseHover;

The handler just logs that event is generated.

void myControl_MouseHover(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine(
        "MouseHover event generated");
}

Generating Mouse Hover event repeatedly

In some scenarios, it could be desirable to generate Mouse Hover event repeatedly inside a control, whenever mouse becomes stationary. For instance, this could be useful if you have a user-drawn control and want to generate Mouse Hover events for individual user-drawn components. To achieve this, we need to reset the Hover event every time it is generated. This can be done by calling TrackMouseEvent method in MouseMove event.

Adding MouseMove event handler…

myControl.MouseMove += myControl_MouseMove;

Calling TrackMouseEvent to reset tracking of Hover event:

void myControl_MouseMove(object sender, MouseEventArgs e)
{
    const uint HOVER_DEFAULT = 0xFFFFFFFF;
    TRACKMOUSEEVENT trackMouseEvent = 
        new TRACKMOUSEEVENT(TMEFlags.TME_HOVER, this.Handle, HOVER_DEFAULT);
    TrackMouseEvent(ref trackMouseEvent);
}

As TrackMouseEvent is a native method, we need to define it using DllImport along with the TRACKMOUSEEVENT structure.

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);

[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct TRACKMOUSEEVENT
{
    public Int32 cbSize;    // using Int32 instead of UInt32 is safe here, and this avoids casting the result  of Marshal.SizeOf()
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
    public TMEFlags dwFlags;
    public IntPtr hWnd;
    public UInt32 dwHoverTime;

    public TRACKMOUSEEVENT(TMEFlags dwFlags, IntPtr hWnd, UInt32 dwHoverTime)
    {
        this.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TRACKMOUSEEVENT));
        this.dwFlags = dwFlags;
        this.hWnd = hWnd;
        this.dwHoverTime = dwHoverTime;
    }
}


/// <summary>
/// The services requested. This member can be a combination of the following values.
/// </summary>
/// <seealso cref="http://msdn.microsoft.com/en-us/library/ms645604%28v=vs.85%29.aspx"/>
[Flags]
public enum TMEFlags : uint
{
    /// <summary>
    /// The caller wants to cancel a prior tracking request. The caller should also specify the type of tracking that it wants to cancel. For example, to cancel hover tracking, the caller must pass the TME_CANCEL and TME_HOVER flags.
    /// </summary>
    TME_CANCEL = 0x80000000,
    /// <summary>
    /// The caller wants hover notification. Notification is delivered as a WM_MOUSEHOVER message.
    /// If the caller requests hover tracking while hover tracking is already active, the hover timer will be reset.
    /// This flag is ignored if the mouse pointer is not over the specified window or area.
    /// </summary>
    TME_HOVER = 0x00000001,
    /// <summary>
    /// The caller wants leave notification. Notification is delivered as a WM_MOUSELEAVE message. If the mouse is not over the specified window or area, a leave notification is generated immediately and no further tracking is performed.
    /// </summary>
    TME_LEAVE = 0x00000002,
    /// <summary>
    /// The caller wants hover and leave notification for the nonclient areas. Notification is delivered as WM_NCMOUSEHOVER and WM_NCMOUSELEAVE messages.
    /// </summary>
    TME_NONCLIENT = 0x00000010,
    /// <summary>
    /// The function fills in the structure instead of treating it as a tracking request. The structure is filled such that had that structure been passed to TrackMouseEvent, it would generate the current tracking. The only anomaly is that the hover time-out returned is always the actual time-out and not HOVER_DEFAULT, if HOVER_DEFAULT was specified during the original TrackMouseEvent request.
    /// </summary>
    TME_QUERY = 0x40000000,
}

Above ensures that Hover event is generated whenever mouse stays still for sometime, and not only once after mouse enters the control.

Book Review: Threading in C# by Joseph Albahari

Threading is a complex subject, it is easy to get yourself entangled in threads which don’t behave as you expect them to. There are many constructs and approaches to synchronize threads or achieve parallelism, each with its own quirks and advantages. There are good old threads, there are thread pools, task parallelism, Parallel class, Async methods and Timers. Then there are a myriad ways of synchronizing thread like locks, spin locks, mutex, semaphores, event wait handles, concurrent collections, Synchronization attribute, Memory Barriers, Interlocked class, Monitor’s Wait/Pulse and Reader Writer Lock . To make sense of it all,  Threading in C# by Joseph Albahari is thorough reference on the subject. It is available online, free of charge in hypertext format which makes it particularly useful as a reference.

csianThreading in C# is also there as a chapter in somewhat abridged form in author’s book ‘C# in a Nutshell‘.

 

Async / Await and SynchronicationContext (C# .Net)

Following innocuous looking async / await code will cause deadlock.

private void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = LongRunningProcess();

  textBox1.Text = task1.Result;
}

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  );

  return txt;
}

To understand why, lets go into what await does in the above case.

1 Execution starts when the button is clicked and button1_Click event is fired on the UI thread.
2 The method, named LongRunningProcess, is invoked.
3 The lamda expression passed to Task.Run() executes in a separate thread (lets call it thread_B)
4 Now await keyword is encountered, rather than completing the rest of the method, control returns back to button1_Click event to continue execution after the call to long running method.
5 Calling task1.Result makes the current thread wait on thread_B to complete and provide the results. So UI thread is now waiting for thread_B to complete.
6 As thread_B completes the task, it has to run the remaining part of long running method. Run time ensures that this code executes on the right context. That is, if the initial part of long running method was executed on the UI thread, then remaining part will also be executed in the same thread context.
7 Therefore, thread_B now attempts to run the remaining part of long running method on UI thread, while UI thread is waiting for thread_B to finish.
8 As UI thread and thread_B are waiting for each other, this creates the deadlock.
How to avoid deadlock?

In this case, deadlock can be avoided by anyone of the following ways:

1- Use await keyword while calling long running method. This makes the button click event asynchronous also.

private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await LongRunningProcess();
}

2- Call ConfigureAwait(false), this will inform the run time that the remaining part of long running method doesn’t need to execute on the UI thread, it can continue running on the thread pool.

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  ).ConfigureAwait(false); //avoids the deadlock

  return txt;
}
Why thread contexts are synchronized?

Consider the UI Controls (Windows Forms or WPF), they are not thread safe. Therefore, any update to the UI controls must be done only from the UI thread. To take care of this, any remaining code after await keyword in an asynchronous method will also execute on the thread context which initiated the method call.

Similarly, in an ASP.Net application, running the code on same thread context is important because the Culture, Principal and other information of the request are stored in the thread.

How thread contexts are synchronized?

To manage all this tricky context synchronization, we have SynchronizationContext class in .Net. There are framework specific implementations (derived classes) for Windows Forms, WPF/Silverlight and ASP.Net which handle the SynchronizationContext in their own ways for the framework to function properly.

The Windows Forms implementation uses Control.Invoke method to accomplish this (more details here). For ASP.NET, execution takes place on a different thread but the context is captured and passed on to the new thread.

There is an excellent article on MSDN regarding the SynchronizationContext which I recommend for details.

 

Creating and Consuming Async methods (C# .Net)

The code we want to run asynchronously could either be CPU-bound or IO-bound. CPU-bound code keeps the CPU busy, requiring intensive processing, calculations etc. On the other hand, IO-bound code frees up the CPU while waiting for an IO operation to complete, for instance, get some data from a web service. Both kinds of asynchronous methods are illustrated below.

 

 Creating Asynchronous method

 

CPU-bound Async method
public async Task<string> OurMethodAsync()
{
  string x = await Task.Run(() =>
    {
      // performs CPU intensive work
      return LongRunningTask();
    });

  return x;
}

Above method doesn’t do anything special. Rather than performing the work itself, it creates a thread and delegates the work to it. It will not make the task run faster, in fact, it may take more time due to multi-threading overhead. One reason to do things this way is to free the calling thread and not keep it busy for long time. This is required in case of User Interface threads, for instance.

 

IO-Bound Async method

For IO operation such as working with file system, requests to web servers etc., .Net framework already provides us with methods which run asynchronously. These methods uses lower levels OS calls to provide asynchronous behavior for blocking IO operations.

Below is our asynchronous method which uses .Net Framework’s WebClient.DownloadStringTaskAsync method.

public async Task<string> GetWebPage(string url)
{
  var webClient = new WebClient();
  string txt = await webClient.DownloadStringTaskAsync(url);

  return txt;
}

 

 Consuming asynchronous method

 

Consuming asynchronous method with await
private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await GetWebPage("http://www.yahoo.com");
}

 

This button click event consumes the IO-bound async method defined above. If GetWebPage method is taking a long time, the control will return back to the caller method. Once results of GetWebPage are available, execution will start again with the instruction after await keyword. This will ensure that the event does not block the UI thread.

Calling asynchronous methods concurrently

We can also use asynchronous method to run tasks in parallel.

private async void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = GetWebPage("http://www.yahoo.com");
  Task<string> task2 = GetWebPage("http://www.google.com");

  await Task.WhenAll(task1, task2);

  textBox1.Text = task1.Result;
  textBox2.Text = task2.Result;
}

 

Notice we are not using await keyword now when invoking GetWebPage method. This causes the return type to change also, we are expecting Task rather than string object.

The flow control is also very different. If GetWebPage is blocking, the control doesn’t return to the caller method, rather execution continues to the next statement in the event.

We have await in the third line which will relinquish control to the caller method if task1 or task2 are not completed yet. When the result of the two tasks are available the last two lines of code are executed on the UI thread.

Keeping UI Responsive (C# .Net)

The User Interface (UI) becomes unresponsive when a time taking operation is executed during an event.

Consider the following button click event where I have simulated a time taking operation by calling Sleep method. In a real scenario, it could be some processing which produces the result to be shown back on the user interface.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";
   // long running operation simulated through Thread.Sleep
   System.Threading.Thread.Sleep(5000);

   textBox2.Text = "Final result";
}

 

Keeping UI responsive through System.Threading.Tasks.Task

To keep the UI responsive, we can spawn a new thread to perform the time taking operation. Earlier, we used to do it with System.Threading.Thread but now we have more convenient Task class from TPL (Task Parallel Library) in .Net.

private void button1_Click(object sender, EventArgs e)
{
   // do initial UI update
   textBox1.Text = "Calculating result…";

   // spawn a new thread for the long running operation and final UI update
   Task.Run(() =>
      {
         System.Threading.Thread.Sleep(5000);
         // unsafe call to UI control
         textBox2.Text = "Final result";
      });
}

 

If we run the above code in debug mode, we get the following exception:

image

UI controls are not thread-safe, therefore, call to the UI should only be made from UI thread which created these controls.

The way around this problem is to use Invoke method of the control and pass it a delegate which performs the required UI changes. Invoke method will ensure that the delegate is executed on the UI thread.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";

   Task.Run(() =>
   {
      System.Threading.Thread.Sleep(5000);

      // using Control.Invoke
      Action act = () => textBox2.Text = "Final result";
      textBox2.Invoke(act);
   });
}

This will keep the UI responsive in a thread safe way.

 

Keeping UI responsive using async / await

Another way of doing this is through async / await keywords.

private async void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Started";

   await Task.Run(() => System.Threading.Thread.Sleep(5000));

   textBox2.Text = "Final result";
}

 

This code will achieve the same results as above.

With async / await, the code looks more synchronous and readable. As await keyword is encountered, a new thread is started for processing the task and the method returns the control back to the caller (this ensures that the UI thread is free and responsive). Once the task is completed, rest of the code for the click event is executed on the UI thread. Behind the scene, compiler generates complex state machine logic to make this happen seamlessly.

Convert C# code to JavaScript

There are some tools which convert C# code to JavaScript. Obviously these will only be useful if your code is not tightly coupled with any C# library as the library won’t be available in JavaScript. These conversion tools may come handy for model classes or any other logic which is, for the most part, independent of .Net framework classes.

The main focus of these tools is not code conversion, rather they primarily try to do for C# what GWT does for Java. They allow you to write code in C#, access the DOM and JavaScript libraries to develop web applications. When the code is compiled, the output is not .Net Application but a web application written in JavaScript and HTML.

 

Conversion Tool Description
duocode duocode is a new tool on the block, currently in beta. It is going to be a commercial software but free to use as of now.duocode uses Microsoft Roslyn and support debugging C# code your compiled JavaScript is running in the browser. It supports pretty comprehensive set of C# feature including Await/Async, C# 6.0 language features, resource files etc.

Homepage: http://duoco.de/

SharpKit SharpKit is commercial (free for open source & small projects) as opposed to the alternatives listed below but does an excellent job of converting C# to JavaScript which is clean and readable. Moreover, it supports all features of C# language.You can see SharpKit live in action here. Give it a C# class or a snippet, it will convert it to JavaScript right there.Sharpkit compares itself with JSC, Script# and GWT at http://sharpkit.net/Compare.aspx

Homepage: http://sharpkit.net/
Google Code: https://code.google.com/p/sharpkit/

JSIL JSIL is a compiler that transforms .NET applications and libraries from their native executable format (CIL bytecode) into standards-compliant, cross-browser JavaScript.There are quite a few demos on JSIL website, one of them allows you to convert C# code to JavaScript right in the browser (though the generated code looks a bit obscure).Homepage: http://jsil.org/
GitHub: https://github.com/sq/JSIL
JSC JSC is an Open Source cross-compiler where you can create web applications for Java, JavaScript, Flash ActionScript, PHP and Google App Engine using Microsoft .NET in C#, VB or F#. And also integrates into the .NET frameworks, Silverlight and ASP.NET.Homepage: http://www.jsc-solutions.net/
Wiki & Tutorials: http://wiki.jsc-solutions.net/
Sourceforge: http://sourceforge.net/projects/jsc/
Script# Script# is a compiler that generate the JavaScript instead of MSIL (Microsoft Intermediate Language) from C# source code like GWT (Google Web Toolkit).Script# supports a subset of language features, for instance enum and struct are not supported.Homepage: http://scriptsharp.com/
GitHub Repository: https://github.com/nikhilk/scriptsharp
Saltarelle Saltarelle is an open source C# to JavaScript compiler. Saltarelle is not an entire framework for web application development (such as GWT), rather it consists of a compiler and a small runtime library that only contains the things necessary for the language features to work. It is, however, designed with interoperability in mind so you can use any existing JavaScript framework with it. It comes with support for jQuery, and other libraries can be used either by authoring an import library (which is just a class / set of classes with special attributes on their members) or by using they ‘dynamic’ feature of C# 4.Homepage: http://www.saltarelle-compiler.com/
Git Repository: https://github.com/erik-kallen/SaltarelleCompiler

For a comprehensive list of tools that convert C# and other languages to JavaScript, visit https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

Developed Custom .Net Font Dialog

Developed a Custom FontDialog as an alternative to the standard .Net FontDialog. Key advantage of CustomFontDialog is the full control over look and feel as it is open source. Source and binary files are available at sourceforge.

CustomFontDialog

CustomFontDialog avoids ‘This is not a True Type Font’ exception that affects the standard dialog in some cases. Most probably the exception happens when some installed fonts have invalid meta information. This exception cannot be caught using try/catch block because the exception is thrown from the code outside .Net framework. The exact exception message is ‘Only TrueType fonts are supported. This is not a TrueType font.’. CustomFontDialog gets around this problem by loading only True Type fonts. More details about the problem with standard dialog can be found here and here.

Moreover, CustomFontDialog provides easy access to recently used fonts by moving them at the top of the list in ‘Recently Used’ section.

Usage

Following C# code snippet demonstrates how to instantiate and display Custom FontDialog.

CustomFontDialog.FontDialog fontDialog = new CustomFontDialog.FontDialog();

// sets the default font
fontDialog.Font = new Font(FontFamily.GenericSansSerif, 10);

if (fontDialog.ShowDialog() == DialogResult.OK) {
   // Font is selected. Get the selected font using 'fontDialog.Font'
}
else {
   // FontDialog is canceled by the user
   // your code here to handle cancel action
}

For the CustomFontDialog to retain the recently selected fonts at the top of the list, the dialog should be instantiated only once and ShowDialog function should be called on the same object whenever the dialog needs to be displayed.

To programmatically add Fonts to be ‘Recently Used Fonts’ section, call AddFontToRecentList method.

Limitation: As compared to the standard FontDialog, CustomFontDialog doesn’t support changing text color.

 

Updates

 

Version 0.2.0 (31-May-2014)

Following fixes and enhancements are included in this version:

1- In Font List, arrow keys can be used to move between ‘Recently Used’ and ‘All Fonts’ sections.
2- When user starts typing in Font List, the focus shifts to the filter Text box automatically.
3- Whenever CustomFontDialog is displayed, the focus is on Font List by default.

Quick and dirty way of creating Numeric TextBox in .Net (C#)

Handle KeyDown event of the TextBox and set the e.Handled property to true if the character is not numeric.

this.myNumericTextBox.KeyDown +=
                       new KeyEventHandler(this.myNumericTextBox_KeyDown); 

 

private void myNumericTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.D0:
                case Keys.D1:
                case Keys.D2:
                case Keys.D3:
                case Keys.D4:
                case Keys.D5:
                case Keys.D6:
                case Keys.D7:
                case Keys.D8:
                case Keys.D9:
                case Keys.End:
                case Keys.Enter:
                case Keys.Home:
                case Keys.Back:
                case Keys.Delete:
                case Keys.Escape:
                case Keys.Left:
                case Keys.Right:
                    break;
                case Keys.Decimal:
                case (Keys)190: //decimal point
                    if (myNumericTextBox.Text.Contains('.'))
                    {
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    }
                    break;
                default:
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    break;
            }

        }

Switch cases list all desired characters which will be displayed, rest of the characters are ignored. If additional characters are required, they may be included as switch cases. For instance, negative sign may be allowed based on your requirement.

How to embed chrome browser in .net application

Chrome browser can be embedded in native application taking a hybrid approach to development where application is partly developed in native technology and partly in web. This has several advantages:

  • Salvage the existing investment in HTML/Javascript projects.
  • The part of application written in web technology is platform independent. This is very important due to variety of devices that are prevalent today.
  • Overcome the limitation of web technology and leverage the full power of the hardware through native code.

We need to know about three projects:

Project Type Description
Chromium Web Browser Chromium is the open source browser project which is behind Google Chrome.
ChromiumEmbedded
(CEF)
Web Browser Control Based on Chromium project, an open source embed-able Web Browser Control is developed called ChromiumEmbedded. ChromiumEmbedded supports programming interface for C++.
Xilium.CefGlue .Net Wrapper Quite a few wrappers are available to make ChromiumEmbedded accessible in other languages. The most updated and active wrapper for .Net is Xilium.CefGlue.

Follow the below steps to embed Chromium Web Browser control in your .Net application.

  1. Download the source code for Xilium from here (Click on the Branches tab and download the Master branch).
  2. Check for the current ChromiumEmbedded (CEF) build supported by Xilium here. As of now, the ChromiumEmbedded supported build is CEF 3.1547.1448. Download the relevant pre build binaries from here.
  3. Unzip the two downloaded files. Copy all DLLs from the Release folder of ChromuimEmbedded and place it in Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  4. Copy the locales folder under Resources from ChromuimEmbedded and place it in the Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  5. Open the Xilium source code in Visual Studio using Xilium.CefGlue.sln. Set CefGlue.Demo.WinForms as the startup project.
  6. Build and run the solution and you will get the demo .Net application running with embedded chromium browser.

Programmatically scroll Listbox in .Net (Windows Forms, C#)

It seems that .Net library doesn’t provide any way to scroll contents of ListBox through code. Selecting an item by setting SelectedIndex automatically scrolls the list to bring the item into view but this may not produce the desired effect. In my case, I wanted to programmatically select an item and make it the first visible item in the list. This effect cannot be achieved through changing SelectedIndex.

The way around this problem is to invoke Windows API SendMessage function.

To call a function from an un-managed DLL, we have to declare it along with DLLImport attribute.

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg,
                                         uint wParam, uint lParam);

As the declaration shows, we have supply four arguments.

S/N Parameter Description
1 IntPtr hWnd This is the handle to ListBox Control. We can get the handle through Handle property of ListBox control e.g. myListBox.Handle
2 uint Msg This should be set as WM_VSCROLL. It says that we want to send message for scrolling vertically. Find list of messages that could be passed to a control here.
3 uint wParam This 32 bit parameter has two parts.

  • Lower 16 bits called LOWORD should specify one of the scroll bar commands. In our case, it should be SB_THUMBPOSITION.
  • Higher 16 bits called HIWORD should specify the numerical value for position of the scroll bar thumb. If we pass the index of a list item, list will scroll such that the item becomes the first visible item in the list.
4 uint lParam This parameter is for additional message specific information. For our purposes, we will just pass 0.

Following is the SendMessage function call to scroll the list. First, we define the constants WM_VSCROLL and SB_THUMBPOSITION. Then we develop the thrid paramter by combining LOWORD and HIWORD. Finally the function is called.

const uint WM_VSCROLL = 0x0115;
const uint SB_THUMBPOSITION = 4;

uint param = ((uint)(lstFont.SelectedIndex) << 16) |
                          (SB_THUMBPOSITION & 0xffff);

SendMessage(myListBox.Handle, WM_VSCROLL, param, 0);