Window Preview Key Events

image_pdfimage_print


   
  

<Window x:Class="RoutedEvents.TunneledKeyPress"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TunneledKeyPress" Height="400" Width="400" PreviewKeyDown="SomeKeyPressed" >
  <StackPanel>
    <Label Margin="5" BorderBrush="Black" BorderThickness="1" HorizontalContentAlignment="Stretch"
           PreviewKeyDown="SomeKeyPressed">
      <StackPanel PreviewKeyDown="SomeKeyPressed">
        <TextBlock Margin="3" HorizontalAlignment="Center" PreviewKeyDown="SomeKeyPressed">
          Image and text label
        </TextBlock>
        <Image Source="c:image.jpg" Stretch="None" PreviewKeyDown="SomeKeyPressed"/>
        <DockPanel Margin="10" PreviewKeyDown="SomeKeyPressed"> 
          <TextBlock Margin="3" PreviewKeyDown="SomeKeyPressed">Type here:</TextBlock>
          <TextBox PreviewKeyDown="SomeKeyPressed" KeyDown="SomeKeyPressed"></TextBox>
        </DockPanel>
      </StackPanel>
    </Label>
    <ListBox Margin="5" Name="lstMessages"></ListBox>
    <CheckBox Margin="5" Name="chkHandle">Handle first event</CheckBox>
    <Button Click="cmdClear_Click" HorizontalAlignment="Right" Margin="5" Padding="3">Clear List</Button>
  </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;

namespace RoutedEvents
{
    public partial class TunneledKeyPress : System.Windows.Window
    {
        public TunneledKeyPress()
        {
            InitializeComponent();
        }

        protected int eventCounter = 0;

        private void SomeKeyPressed(object sender, RoutedEventArgs e)
        {
            eventCounter++;
            string message = "#" + eventCounter.ToString() + ":
" +
                " Sender: " + sender.ToString() + "
" +
                " Source: " + e.Source + "
" +
                " Original Source: " + e.OriginalSource + "
" +
                " Event: " + e.RoutedEvent;
            lstMessages.Items.Add(message);
            e.Handled = (bool)chkHandle.IsChecked;
        }

        private void cmdClear_Click(object sender, RoutedEventArgs e)
        {
            eventCounter = 0;
            lstMessages.Items.Clear();
        }
    }
}

   
    
     


Non-Rectangular window

image_pdfimage_print


   
  

<Window x:Class="Windows.TransparentWithShapes"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NonRectangularWindowSample" Width="210" Height="170"
  WindowStyle="None" AllowsTransparency="True" Background="Transparent">
  <Grid>
    <Path Stroke="DarkGray" StrokeThickness="1" SnapsToDevicePixels="True">

      <Path.Fill>
        <LinearGradientBrush StartPoint="0.2,0" EndPoint="0.8,1" >
          <LinearGradientBrush.GradientStops>
            <GradientStop Color="White"  Offset="0"></GradientStop>
            <GradientStop Color="White"  Offset="0.45"></GradientStop>
            <GradientStop Color="LightBlue" Offset="0.9"></GradientStop>
            <GradientStop Color="Gray" Offset="1"></GradientStop>
          </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
      </Path.Fill>

      <Path.Data>
        <PathGeometry>
          <PathGeometry.Figures>
            <PathFigure StartPoint="20,0" IsClosed="True">
              <LineSegment Point="140,0"></LineSegment>
              <ArcSegment Point="160,20" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
              <LineSegment Point="160,60"></LineSegment>
              <ArcSegment Point="140,80" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
              <LineSegment Point="70,80"></LineSegment>
              <LineSegment Point="20,80"></LineSegment>
              <ArcSegment Point="20,0" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
            </PathFigure>
          </PathGeometry.Figures>
        </PathGeometry>
      </Path.Data>
      <Path.RenderTransform>
        <ScaleTransform ScaleX="1.3" ScaleY="1.3"></ScaleTransform>
      </Path.RenderTransform>

    </Path>

    <StackPanel Margin="5">
      <Button HorizontalAlignment="Right" Click="cmdClose_Click" Margin="0,5,10,0">x</Button>
    </StackPanel>
  </Grid>
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Input;

namespace Windows {

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

        private void window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void cmdClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}

   
    
     


Set a Default Button

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="100" Width="300">
    <DockPanel>
        <TextBox DockPanel.Dock="Top" Margin="5">Button three is the default button.</TextBox>
        <StackPanel HorizontalAlignment="Center" DockPanel.Dock="Bottom" Orientation="Horizontal">
            <Button Click="SharedButtonClickHandler" Content="Button One" Name="btnOne" Width="75" />
            <Button Click="SharedButtonClickHandler" Content="Button Two" Name="btnTwo" Width="75" />
            <Button Click="SharedButtonClickHandler" Content="Button Three" IsDefault="True" Margin="5" Name="btnThree" />
        </StackPanel>
    </DockPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void SharedButtonClickHandler(object sender,RoutedEventArgs e)
        {
            Button source = e.OriginalSource as Button;

            if (source != null)
            {
                MessageBox.Show("You pressed " + source.Name, Title);
            }
        }
    }
}

   
    
     


Use the Grid to create a dialog box that uses the WPF layout API

image_pdfimage_print


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="Grid_Run_Dialog.Window1"
    Name="mainWindow" Loaded="onLoaded" Width="425" Height="200"/>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Grid_Run_Dialog
{
  public partial class Window1 : Window
  {
    Grid grid1 = new Grid ();
    ColumnDefinition colDef1 = new ColumnDefinition();
    ColumnDefinition colDef2  = new ColumnDefinition();
    ColumnDefinition colDef3 = new ColumnDefinition();
    ColumnDefinition colDef4 = new ColumnDefinition();
    ColumnDefinition colDef5 = new ColumnDefinition();
    RowDefinition rowDef1= new RowDefinition();
    RowDefinition rowDef2= new RowDefinition();
    RowDefinition rowDef3= new RowDefinition();
    RowDefinition rowDef4= new RowDefinition();
    TextBlock txt1 = new TextBlock();
    TextBlock txt2 = new TextBlock();
    Button button1= new Button();
    Button button2= new Button();
    Button button3= new Button();
    TextBox tb1;
    Image img1 = new Image();

        void onLoaded(object sender, EventArgs e)
    {
            grid1.Background = Brushes.Gainsboro;
            grid1.HorizontalAlignment = HorizontalAlignment.Left;
            grid1.VerticalAlignment = VerticalAlignment.Top;
            grid1.ShowGridLines = true;
            grid1.Width = 425;
            grid1.Height = 165;

            colDef1.Width = new GridLength(1, GridUnitType.Auto);
            colDef2.Width = new GridLength(1, GridUnitType.Star);
            colDef3.Width = new GridLength(1, GridUnitType.Star);
            colDef4.Width = new GridLength(1, GridUnitType.Star);
            colDef5.Width = new GridLength(1, GridUnitType.Star);
            grid1.ColumnDefinitions.Add(colDef1);
            grid1.ColumnDefinitions.Add(colDef2);
            grid1.ColumnDefinitions.Add(colDef3);
            grid1.ColumnDefinitions.Add(colDef4);
            grid1.ColumnDefinitions.Add(colDef5);

            rowDef1.Height = new GridLength(1, GridUnitType.Auto);
            rowDef2.Height = new GridLength(1, GridUnitType.Auto);
            rowDef3.Height = new GridLength(1, GridUnitType.Star);
            rowDef4.Height = new GridLength(1, GridUnitType.Auto);
            grid1.RowDefinitions.Add(rowDef1);
            grid1.RowDefinitions.Add(rowDef2);
            grid1.RowDefinitions.Add(rowDef3);
            grid1.RowDefinitions.Add(rowDef4);

            img1.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("fil:///c:/image.png", UriKind.Relative));
            Grid.SetRow(img1, 0);
            Grid.SetColumn(img1, 0);

            txt1.Text = "Text";
            txt1.TextWrapping = TextWrapping.Wrap;
            Grid.SetColumnSpan(txt1, 4);
            Grid.SetRow(txt1, 0);
            Grid.SetColumn(txt1, 1);

            txt2.Text = "Open:";
            Grid.SetRow(txt2, 1);
            Grid.SetColumn(txt2, 0);
            
            Grid.SetRow(tb1, 1);
            Grid.SetColumn(tb1, 1);
            Grid.SetColumnSpan(tb1, 5);
            
            button1.Content = "OK";
            button2.Content = "Cancel";
            button3.Content = "Browse ...";
            Grid.SetRow(button1, 3);
            Grid.SetColumn(button1, 2);
            button1.Margin = new Thickness(10, 0, 10, 15);
            button2.Margin = new Thickness(10, 0, 10, 15);
            button3.Margin = new Thickness(10, 0, 10, 15);
            Grid.SetRow(button2, 3);
            Grid.SetColumn(button2, 3);
            Grid.SetRow(button3, 3);
            Grid.SetColumn(button3, 4);
            
            grid1.Children.Add(img1);
            grid1.Children.Add(txt1);
            grid1.Children.Add(txt2);
            grid1.Children.Add(tb1);
            grid1.Children.Add(button1);
            grid1.Children.Add(button2);
            grid1.Children.Add(button3);
            
            mainWindow.Content = grid1;

        }
    }
}

   
    
     


Center a Window to Screen

image_pdfimage_print


   
  
<Window x:Class="Windows.CenterScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="CenterScreen" Height="300" Width="300"
    >
  <Button Margin="15" Click="cmdCenter_Click">Center Me</Button>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;
using System.ComponentModel;

namespace Windows
{
    public partial class CenterScreen : System.Windows.Window
    {
        public CenterScreen()
        {
            InitializeComponent();
        }

        private void cmdCenter_Click(object sender, RoutedEventArgs e)
        {            
            double height = SystemParameters.WorkArea.Height;
            double width = SystemParameters.WorkArea.Width;            
            this.Top = (height - this.Height) / 2;            
            this.Left = (width - this.Width) / 2;            
         
        }
    }
}

   
    
     


Windows Transparent Background

image_pdfimage_print


   
  

<Window x:Class="Windows.TransparentBackground"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Windows" Height="300" Width="300"
    WindowStyle="None" AllowsTransparency="true">
  <Window.Background>    
    <ImageBrush ImageSource="c:image.png"></ImageBrush>
  </Window.Background>
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
      </Grid.RowDefinitions>
      <Button Margin="20" Grid.Row="2">Close</Button>   
    </Grid>
</Window>


//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;

namespace Windows
{
    public partial class TransparentBackground : System.Windows.Window
    {
        public TransparentBackground()
        {
            InitializeComponent();
        }

    }
}

   
    
     


Save Window Position to Registry

image_pdfimage_print


   
  

<Window x:Class="Windows.SavePosition"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SavePosition" Height="300" Width="300" >
  <StackPanel Margin="10">
    <Button Click="cmdSave_Click">Save Position</Button>
    <Button Click="cmdRestore_Click">Restore Position</Button>
  </StackPanel>
</Window>
//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;
using Microsoft.Win32;
 
namespace Windows
{
    public partial class SavePosition : System.Windows.Window
    {
        public SavePosition()
        {
            InitializeComponent();
        }

        private void cmdSave_Click(object sender, RoutedEventArgs e)
        {
            WindowPositionHelper.SaveSize(this);
        }

        private void cmdRestore_Click(object sender, RoutedEventArgs e)
        {
            WindowPositionHelper.SetSize(this);
        }
    }
    public class WindowPositionHelper
    {
        public static string RegPath = @"SoftwareMyApp";
        
        public static void SaveSize(Window win)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(RegPath + win.Name);
            key.SetValue("Bounds", win.RestoreBounds.ToString());            
        }

        public static void SetSize(Window win)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RegPath + win.Name);
            if (key != null)
            {
                Rect bounds = Rect.Parse(key.GetValue("Bounds").ToString());

                win.Top = bounds.Top;
                win.Left = bounds.Left;
                if (win.SizeToContent == SizeToContent.Manual)
                {
                    win.Width = bounds.Width;
                    win.Height = bounds.Height;
                }
            }
        }
    }

}