Switch On The Code RSS Button - Click to Subscribe
Oct
2

WPF Tutorial - Getting the DoubleClick Event

In WinForms, everything that derived from System.Windows.Forms.Control had the MouseDoubleClick event - and not suprisingly, in WPF, everything derived from System.Windows.Controls.Control also has a MouseDoubleClick event. But there is a key difference - in WinForms, almost everything that gets displayed on the screen is derived from System.Windows.Forms.Control in some way - while in WPF, there are a number of items you can put on the screen that do not actually derive from System.Windows.Controls.Control. So today we are going to take a look at how to get double clicks when you are not derived from System.Windows.Controls.Control.

To figure this out, we are going to write a little app with a TextBlock - and when you double click on the TextBlock, it switches to a TextBox where you can edit the text. When you are done editing the text, you can double click in the TextBox, and it switches back to the TextBlock with the new text that you have entered. You can see screenshots of the two states of this simple app below:



Ok, so the issue here is that TextBlock does not derive from Control (it derives from FrameworkElement), so it does not have a MouseDoubleClick event to attach to. So what do we do? Well, it is actually really simple - lets take a look at the xaml behind this sample app first:

<Window x:Class="DoubleClickTest.DoubleClickWindow"
    xmlns=
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DoubleClickTest" Height="100" Width="200"
    x:Name="MyWindow">

  <Canvas Margin="10">
    <TextBlock Name="MyBlock" MouseDown="MyBlock_MouseDown"
        Text="{Binding ElementName=MyWindow, Path=MyText}"/>

    <TextBox Visibility="Collapsed" Name="MyBox"
        MouseDoubleClick="MyBox_MouseDoubleClick">

      <TextBox.Text>
        <Binding Path="MyText" ElementName="MyWindow"
            UpdateSourceTrigger="PropertyChanged" />

      </TextBox.Text>
    </TextBox>
  </Canvas>
</Window>

So as you can see, we just have a TextBlock and a TextBox, one visible and one not. On the TextBox we have attached to the MouseDoubleClick event, and on the TextBlock we have attached to the MouseDown event. So, as you might have suspected, we will be using the MouseDown event to figure out if a double click has occurred. So onto the code behind:

public partial class DoubleClickWindow : Window
{
  public DoubleClickWindow()
  {
    InitializeComponent();
  }

  public string MyText
  {
    get { return (string)GetValue(MyTextProperty); }
    set { SetValue(MyTextProperty, value); }
  }

  public static readonly DependencyProperty MyTextProperty =
      DependencyProperty.Register("MyText", typeof(string),
        typeof(DoubleClickWindow),
        new UIPropertyMetadata("This Is Some Text Of Mine"));

  private void MyBlock_MouseDown(object sender,
      MouseButtonEventArgs e)
  {
    if (e.ClickCount == 2)
    {
      MyBlock.Visibility = Visibility.Collapsed;
      MyBox.Visibility = Visibility.Visible;
    }
  }

  private void MyBox_MouseDoubleClick(object sender,
      MouseButtonEventArgs e)
  {

    MyBox.Visibility = Visibility.Collapsed;
    MyBlock.Visibility = Visibility.Visible;
  }
}

So here we have the whole code behind class for DoubleClickWindow. Not much here, just a constructor, the dependency property that the TextBlock and TextBox are bound to, and the two event functions.

And it is one of those event functions that we care about - the MyBlock_MouseDown method. And what do we have here - a ClickCount number in the MouseButtonEventArgs! The ClickCount property holds the number of times the mouse button has been clicked within the system double click time (you know, that slider for double click speed in the mouse control panel). If you want to know if the user has clicked twice, you just have to check and see if the ClickCount is equal to 2 - and that is exactly what we do here. If it is equal to 2, we switch the visibilities on the TextBlock and the TextBox.

The interesting thing about the ClickCount is that you can do something like listen for a triple or even quadruple click. I have no idea why you would want to do such a thing :P - but it is possible. You can also get this information in any click or mouse up event (or any of the corresponding preview events) - any event that gives you the MouseButtonEventArgs as the argument to the event will have the click count information.

Oh, and I suppose we can't forget the last function in the class - MouseDoubleClick, which is hooked to the actual double click event on the TextBox. Of course here we don't have to check if it is a double click (the code wouldn't be executing otherwise) - we just flip the visibilities back. And, just as a side note, if you dive down into the code of Control (where this double click event comes from), you find that all they are doing is triggering the event when the ClickCount of the current mouse down event is equal to 2.

Hope that cleared up any confusion that you may have had about double click events in WPF! I know I was confused for a little while as to why there wasn't a MouseDoubleClick event available everywhere. As always, please leave and questions in the comments and I'll do my best to answer them.



Posted in WPF, XAML, C#, All Tutorials by The Tallest | No Comments »

Oct
1

Creating Your First AutoHotkey Script

AutoHotkey Icon

Working and living as a programmer means I am pretty much on my computer or playing around on it all the time - sometimes maybe too much. I am sure many of you out there can relate. This also means I am always looking for tools to make my life easier. As of late I have found AutoHotkey to be a really cool time saving application. Well today I am going to show you how to create an AutoHotkey script that will help reduce redundant work.

Now, I am guessing most of you are asking "What is AutoHotkey?". From my interaction with it the short answer is: a utility to help automate tasks. The long version is that AutoHotkey is an application that allows for scripts to be ran that can define global hotkeys or execute programs or can be used to build applications that utilize AutHotkey's functionality. There are almost endless possibilities of what can be done with the tool. AutoHotkey is limited to Windows only however, sorry mac and linux geeks.

Today, however, we are going to start by creating a very simple script. The script we are going to create will do a few things. The first thing we are going to do is create a hotkey that will open up Notepad++, my text editor of choice. We will then create a hotkey that will present us with an input box and then will search this site, Switch on the Code, for whatever was put in the input box. Lastly, we will add a piece of code that will be auto executed when our script starts up - in my case when Windows starts.

To get the ball rolling you first need to download and install the AutoHotkey application. This should go really quick the download is less than 2MB currently and should only take a few seconds to install. Ok now that that is out of the way we can get to coding. Open up your text editor of choice and create a new document. The very first thing we are going to build is a "Hello World" script.

Our hello world script is going to create a message box and print out "Hello World". To accomplish this we will take advantage of the MsgBox command available in AutoHotkey. This function can simply be called with some text attached. The following code demonstrates this. Notice that after the function name there is a comma.

MsgBox, Hello World

To run this we save the file, I named mine AutoHotkey.ahk (the .ahk is important), and then just double click the script file or right click and select "Run Script". This should popup a window like below. We can click the "OK" button and continue on. AutoHotkey System Tray IconAlso in your system try you will see an icon like the one to the right. This shows that the script is running, meaning that any hotkeys that defined in the script file are usable at this time. We can also right click the system try icon to pause, edit, reload, and exit the script.

AutoHotkey Hello World Popup

An AutoHotkey script file is setup in the following manner, all the code you want automatically executed (like our "Hello World" message) goes at the top of the file and doesn't have any identifiers attached. Identifiers are what are used to create hotkeys and more. To declare a hotkey we need to put an identifier for which keys it will be bound to and then what code to run. Now, lets go ahead and clear our script file and enter the following code.

#n:: Run notepad++

This code creates a hotkey which is tied to the combination of the "Windows key + n" (Windows key is pressed plus the 'n' key is pressed). When this hotkey is pressed the script will Run notepad++ which simply opens notepad++. So the basic hotkey syntax is key(s) to press:: code to run. The "::" separates the two items but can't have a space after the key(s) to press. As mentioned earlier the "#" symbol represents the Windows key. The other basic symbols are as follows:

Shortcut Symbol Key Description
# Windows Key
^ Control Key
! Alt Key
+ Shift Key

This is only a partial list but includes the most used ones; you can get a complete list from the AutoHotkey Symbols Documentation. So your first hotkey has been created. The next hotkey we are going to develop is multiline so the syntax is slightly different. The input key identifier is setup the same way but we now have multiple lines of code after the identifier. To end the code we add a return call. The code for the new hotkey follows. I will go over the specifics after.

#s::
InputBox, SearchTerm, Search SOTC, Please enter search term.
if not ErrorLevel
{
  if SearchTerm <> ""
    Run http://blog.paranoidferret.com/index.php?s=%SearchTerm%&Submit=Search
}
return

So, that looks a bit more complicated than the first hotkey we built. The code starts off by prompting the user for some input. A input box is created and shown using the InputBox command. The first parameter for this command (again after the first comma) is the output variable - where the string entered into the input box is stored. The second is the window title and third is the prompt text. You can see a image of this prompt below. The next line is an if statement to check if the ErrorLevel has been set by any faults when entering data into the input box. If no errors have occurred we check to make sure the string isn't blank. If SearchTerm is not blank we tell windows to go to the Switch on the Code blog with the GET parameters s set to the search term and Submit equal to "Search". This searches our blog with the entered search info.

AutoHotkey STOC Search Input

The final thing we are going to do today is add an auto executing piece of script to the top of our script. This code will make the windows taskbar semi transparent. To make the taskbar or any window transparent you can use the WinSet command. The command takes a few parameters. The first parameter is the attribute to set on the window in this case we set it to Transparent. The next parameter is the value of transparency which can be any value from 0 (invisible) to 255 (fully opaque). The final parameter for this is the window to change transparency on. For our call we use a special constant, ahk_class Shell_TrayWnd, which refers to the taskbar.

WinSet, Transparent, 180, ahk_class Shell_TrayWnd

That wraps up this tutorial. The only thing left to show you is the completed script file.

WinSet, Transparent, 180, ahk_class Shell_TrayWnd

#n:: Run notepad++

#s::
InputBox, SearchTerm, Search SOTC, Please enter search term.
if not ErrorLevel
{
  if SearchTerm <> ""
    Run http://blog.paranoidferret.com/index.php?s=%SearchTerm%&Submit=Search
}
return

I hope that this tutorial helps you get up and running with AutoHotkey. If you have any questions or concerns please leave a comment. I would also love to hear whether or not people are interested in more AutoHotkey tutorials. Lastly, feel free to download the script we created today from the references list below.

References



Posted in AutoHotkey, All Tutorials by The Fattest | No Comments »