Saturday, November 23, 2013

Moving Ellipse in Canvas using keyboard Events

This is a simple code that you can understand easily. Here KeyboardDown event is used which means whether any keyboard is pressed down. Don't mix it with down key arrow which I have mentioned in code.

XAML CODE
<Window x:Class="workingWithText1.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" KeyDown="Window_KeyDown_1">
    <Grid>
        <Canvas Background="Green">
            <Ellipse Name="ball" Fill="WhiteSmoke" Width="100" Height="100"></Ellipse>
        </Canvas>
    </Grid>
</Window>


XAML.CS CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace workingWithText1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        int i = 0;
        private void Window_KeyDown_1(object sender, KeyEventArgs e)
        {
            if ((Keyboard.GetKeyStates(Key.Down) & KeyStates.Down) > 0)
            {
                Canvas.SetTop(ball, i++);
            }

            if ((Keyboard.GetKeyStates(Key.Left) & KeyStates.Down) > 0)
            {
                Canvas.SetLeft(ball, i--);
            }

            if ((Keyboard.GetKeyStates(Key.Right) & KeyStates.Down) > 0)
                Canvas.SetLeft(ball, i++);

            if ((Keyboard.GetKeyStates(Key.Up) & KeyStates.Down) > 0)
                Canvas.SetTop(ball, i--);
        }
    }
}

Note:
Here you can take multiple variables in place of for smooth motion.