In Image Processing applications it is sometimes necessary to move a selected image (or part of image) to place at a specific position. For example, it is applicable to Form Processing, where predefined templates of different forms exist. When you select an image and place a predefined template on top of the image, it may happen that the position of the image needs to be adjusted to align it with the template. In such cases, you can use keyboard arrow keys to move the image horizontally and/or vertically.
We are exploring the same in a Windows app built with .NET, C#, and WPF. We have found several ways of moving the image when the image control is placed within a Canvas. Canvas is used as a container in WPF, where you can place several controls, but this case is a bit different. Here the image control is not placed within a Canvas – a different container has been used to place the image.
To achieve the image movement functionality, the PreviewKeyDown event can be used for Image control. This event occurs when a key is pressed, while the focus is on the image control. So, the first part is over, i.e., connect the arrow keys with the image control. The next question is how to move the image? For this set the image control’s margin whenever a specific keyboard key is pressed. Here is some code to alter the margin for the image control.
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
switch(e.Key)
{
case Key.Left:
leftMargin -= 5;
e.Handled = true;
break;
case Key.Right:
leftMargin += 5;
e.Handled = true;
break;
case Key.Up:
topMargin -= 5;
e.Handled = true;
break;
case Key.Down:
topMargin += 5;
e.Handled = true;
break;
default:
MessageBox.Show(“Invalid key pressed”);
break;
}
this.image1.Margin = new Thickness(leftMargin,
topMargin,
rightMargin,
bottomMargin
);
}
In the above code, say the image control currently has the focus and you want to move the image to the left. For that just press the left arrow key. Then the PreviewKeyDown event is called and it comes to the Key.Left case, which decreases the left margin by 5. In effect, you will see the image move to the left. The movements toward right, top, and bottom also work the same way.
Please remember the following points:
- The image control must have focus.
- Set the KeyPressEventArgs.Handled property to TRUE – it will cancel the KeyPress event; otherwise, the image control will loose focus and the PreviewKeyDown event will not called on arrow key press.
Enjoy playing with images in a WPF application on Windows.
Excellent Post! Thanks for sharing the information. Very informative blog post.