Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, February 20, 2009

RegisterHotKey in C#

I like .Net framework for its huge class library covering almost anything you'll ever need. One thing I could not find was registering a windows hot-key in C#. It seems the framework does not provide a solution for system-wide hot keys. So I had to use the good old RegisterHotKey Win32 function.

To call it from C#, you need to use P/Invoke service to invoke the unmanaged function residing in user32.dll

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

The hWnd parameter is the handle of a form that will receive WM_HOTKEY message. To get the handle of a Form simply use Handle property. In order to process WM_HOTKEY message, your form needs to override WndProc method.

Just one more thing you should know: RegisterHotKey and ShowInTaskBar property don't mix well. It seems that a new window is created each time ShowInTaskBar property is called so your WndProc mehod will stop recieving hot-keys. You need to RegisterHotKey again because Handle property returns a new window handle after ShowInTaskBar was called.

Saturday, February 02, 2008

When IHTMLWindow2.document throws UnauthorizedAccessException

This is basically a C# translation of one of my older articles "When IHTMLWindow2::get_document returns E_ACCESSDENIED". Some .Net people encountered difficulties to use it, so I decided to make their life easier.

The main problem is the confusion created by System.IServiceProvider .Net interface because it has the same name as the COM interface. Once this issue is passed the code translation is straightforward. Here's the interop code to declare the COM interface IServiceProvider.
// This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface!
[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)][PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}
You find here full source code of the sample assembly.

This technique was successfully implemented and tested in Twebst web automation library.