Jan 062015
 
 January 6, 2015  Posted by at 1:05 pm C# & F# Tagged with:  Add comments

EDIT: Ah yes, I knew I had to add disclaimers of all sorts. Here is one: yes you can call the the win32 dll directly in C#- which I assume most C# devs know about. The example below is based of a script I wrote earlier with AHK so I used what i had lying around. AHK is for desktop automation with keyboard shortcuts (‘hot keys’), and there is a lot you can do. This is an *example* of using the DLL with the wrapper, and a Hello World seemed too boring. The example shows how to create a function for changing screen size, and then creating hot keys for for desired screen resolution.
Disclaimer 2: You can download the AHK executable if you just want to write scripts- you don’t need to use the DLL as explained in this old post of mine: What is AutoHotKey, macros, automation software, hotkeys and scripts?
Disclaimer 3: I’ll update the post with something more fun at some point

In C# you could also have fun with the following for global hot keys if you wanted to have the solution entirely in C#:
[sourcecode language=”csharp”]
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[/sourcecode]

Anyway, enough disclaimers, here is the AHK dll example.

As you probably know I’m a big fan of the desktop automation tool AutoHotKey, and while I had Danny and Jonas over for another night of coding I decided to try out the DLL. There is a lovely wrapper provided by Andrew Smith that manages the interop so we don’t have to register the DLL- which certainly makes it easier to get up and running. This is a little guide on setting up a simple project based of the screen switcher script I shared a year back. Switching screen resolution can be done directly in C#, but in this example we are simply creating hot keys for specific screen resolutions, a combination of CTRL + chosenNumber. Error handling and validation omitted (for example, make sure the user doesn’t try to set the same hotkey twice). I’m sure you can think of something more fun to do with AHK but my blood sugar is low 😛

Grab the source code for the wrapper on GitHub here

AutoHotKeyDll used with csharp1

Add a reference in your project to the AutoHotKey.Interop.DLL. If it is missing from source code downloaded you might have to build the interop project to create the DLL.

AutoHotKeyDll used with csharp
AutoHotKeyDll used with csharp2




 

Once you have the DLL you can simply create a new instance of AutoHotkeyEngine. It has a few functions, well documented on the GitHub page. We are only going to use the ExecRaw() function which executes the string passed in (script).

Here is the code for my simple example:

[sourcecode language=”csharp”]
using System;
using System.Windows;
using AutoHotkey.Interop;

namespace AhkDllExample
{
public partial class MainWindow
{
private readonly AutoHotkeyEngine _ahkEngine = new AutoHotkeyEngine();

private const string ScreenSwitcherFunction = @"ChangeResolution(w,h) {
VarSetCapacity(dM,156,0)
NumPut(156,dM,36)
NumPut(0x5c0000,dM,40)
NumPut(w,dM,108)
NumPut(h,dM,112)
DllCall( ""ChangeDisplaySettingsA"", UInt,&dM, UInt,0 )
}";

public MainWindow()
{
InitializeComponent();

_ahkEngine.ExecRaw(ScreenSwitcherFunction);

OutputTextBlock.Text = ScreenSwitcherFunction;
}

string CreateHotKey()
{
return string.Format(@"^{0}::ChangeResolution({1},{2})return",
int.Parse(nr.Text),
int.Parse(x.Text),
int.Parse(y.Text));
}

private void OnSetHotKey(object sender, RoutedEventArgs e)
{
var hotKey = CreateHotKey();
_ahkEngine.ExecRaw(hotKey);
OutputTextBlock.Text = "Hot Key set : " + Environment.NewLine;
OutputTextBlock.Text += hotKey;
}
}
}

[/sourcecode]

Image of the code, in case WordPress messes up my code again:

AutoHotKeyDll used with csharp3

And the View for those that aren’t familiar with XAML:
[sourcecode language=”xml”]
<Window x:Class="AhkDllExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<TextBlock Padding="20,90,0,0"
FontSize="17"
FontWeight="ExtraLight"
x:Name="OutputTextBlock"
TextWrapping="Wrap"
Background="#FF3E3D3C"
Foreground="#FFA1EEFF" />
<StackPanel Orientation="Horizontal">
<TextBox x:Name="x"
Height="50"
TextAlignment="Center"
Width="100"
FontSize="25"
Text="1024"
VerticalAlignment="Top" />
<TextBlock Text="X"
FontSize="25"
Margin="20,10"
Foreground="Wheat" />
<TextBox x:Name="y"
Height="50"
TextAlignment="Center"
Width="100"
FontSize="25"
Text="768"
VerticalAlignment="Top" />
<TextBox x:Name="nr"
Height="50"
TextAlignment="Center"
Width="100"
FontSize="25"
Margin="20,0"
Text="9"
VerticalAlignment="Top" />
<Button BorderBrush="Wheat"
Content="Set HotKey"
FontSize="20"
Height="50"
FontWeight="ExtraLight"
Foreground="Wheat"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Padding="10"
Background="#FF7C1041"
Click="OnSetHotKey" />
</StackPanel>

</Grid>
</Window>

[/sourcecode]

 

Once the key combo has been set I can use CTRL + 9 (or something else if values are changed) to change my screen resolution. Result:

AutoHotKeyDll used with csharp4

AutoHotKeyDll used with csharp5

AutoHotKeyDll used with csharp6

 

Happy coding!

 

 

 

 

  3 Responses to “Using AutoHotKey.dll with C# (in a WPF application)”

  1. No AutoHotKey.Interop nuget package? sad panda.

    –larsw

  2. Thank you !

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 11 + 7 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)