Posted by: Zeeshan Amjad | November 9, 2009

Calling Windows API from WPF Application

Sometimes we want to access the low level functionality of operating system which is not directly available in WPF. In that case we are going to call Windows API directly. Calling a Windows API from WPF program is similar to calling it from any console based .Net program. Let’s take a look at the example and calling two Windows API in our program to make non rectangular window. We are going to create a region with CreateRoundRectRgn and then set the current window region by calling SetWindowRgn. The only difference between calling API from Windows Form or any other .Net based program and WPF is that here we don’t have direct access to handle of window i.e. HWND. We have to use WindowInteropHelper class to get the handle of window. Here is a class diagram of WindowInteropHelper class.


Here is a complete XAML code of this project.

  1: <Window x:Class="PInvokeWPF.Window1"
  2:     xmlns=""
  3:     xmlns:x=""
  4:     Title="PInvoke WPF" Height="300" Width="300" Loaded="Window_Loaded">
  5:     <Grid>
  7:     </Grid>
  8: </Window>

Here is the complete C# code of the project.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Windows;
  6: using System.Windows.Controls;
  7: using System.Windows.Data;
  8: using System.Windows.Documents;
  9: using System.Windows.Input;
 10: using System.Windows.Media;
 11: using System.Windows.Media.Imaging;
 12: using System.Windows.Navigation;
 13: using System.Windows.Shapes;
 14: using System.Runtime.InteropServices;
 15: using System.Windows.Interop;
 17: namespace PInvokeWPF
 18: {
 19:     /// <summary>
 20:     /// Interaction logic for Window1.xaml
 21:     /// </summary>
 22:     public partial class Window1 : Window
 23:     {
 24:         [DllImport("user32.dll")]
 25:         static extern Int32 SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);
 27:         [DllImport("gdi32.dll")]
 28:         static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2, int cx, int cy);
 30:         public Window1()
 31:         {
 32:             InitializeComponent();
 33:         }
 35:         private void Window_Loaded(object sender, RoutedEventArgs e)
 36:         {
 37:             IntPtr hwnd = new WindowInteropHelper(this).Handle;
 38:             SetWindowRgn(hwnd, CreateRoundRectRgn(0, 0, 300, 300, 75, 75), true);
 39:         }
 40:     }
 41: }

Here is the output of this program.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: