It is possible to host WPF controls in a Win32 application, and the other way around, but because of the differences betweeb these technologies there are various issues that can appear. One of these is handling of keyboard input. Without diving too much into differences between WPF and Win32, I will show how to provide keyboard input for WPF controls hosted in a Win32 applications. For reading about the differences and the interoping between the two I suggest WPF and Win32 Interoperation.

Hosting a WPF Control in Win32

To host a WPF control in a Win32 application you need to follow several steps.

  • Create a new HwndSource, setting the parent window as it’s parent. This is a key object, that enables displaying of WPF content in a Win32 window.
  • Instantiate the WPF control or window
  • Assign the reference to this instance of the WPF control or window RootVisual property of the HwndSource object.

To simplify this process, I have this small helper class:

With this class I can create WPF controls like this:

Enabling Keyboard Input

While you can use the mouse with these WPF controls added like this, the keyboard in not enabled. To provide keyboard input for the WPF controls, we need to hook the HwndSource, adding a handler that receives all window messages. We must handle the WM_GETDLGCODE message to let the system know what kind of messages we want to handle on our own (in the WPF control).

This is how we add the hook:

And this is how the hook procedure looks (defined as a static member of my CWpfControlWrapper):

By returning all these dialog codes will let the system know that the window wants to process arrow keys, tab keys, all keys and receive the WM_CHAR message.

Enabling TAB Navigation

Even though the WPF controls now have keyboard input, it turns our that navigating with TAB (forward) or TAB+SHIFT (backwards) does not work.

Here is an example where I have an MFC application with four WPF controls, two buttons and two text boxes. One button and one text box, as well as the OK and CANCEL buttons have tab stops.

The sample dialog box looks like this:

Pressing the TAB key should allow navigating from button 1 to edit 1, then button OK, button CANCEL and then back to button 1. Button 2 and edit 2, not having the tab stop style defined, should not be included in the navigation.

As already mentioned, this does not work, however. After reading about a solution for this problem, it looked like the key lied in the IKeyboardInputSink interface, that both HwndSource and HwndHost implement. This interface provides a keyboard sink for components that manage tabbing, accelerators, and mnemonics across interop boundaries and between HWNDs. Apparently the solution was to:

  • derive the HwndSource class
  • override the TabInto method (actually, since this is a sealed method you’d have to define a new override for it) and implement there the tabbing logic
  • use this derived HwndSource to present WPF content in a Win32 window

Though I tried several things I didn’t manage to make it work. However, since I already had a hook for all window messages, and explicitly asked for receiving WM_CHAR, it was possible to use this to handle TAB and TAB+SHIFT. So here is an addition to the ChildHwndSourceHook above:

So if we get a WM_CHAR and the wParam is VK_TAB, then we query the parent for the next tab stop (for forward navigation if SHIFT was not pressed, or backwards navigation if SHIFT was also pressed). If there is such a tab stop we set focus on that window.

The FindNextTabStop method (added as a member of the CWpfControlWrapper class) looks like this:

It does the following:

  • it gets the next/previous window in the z-order (which defines the tab stop order)
  • when it reaches the end/top of the z-order, it starts all over again, which enables looping through the child windows of the parent
  • if the next child the in z-order is the current control, then it finished looping through the children of the parent and it stops
  • if the current child in the z-order has the WS_TABSTOP style set, then this is the window we are looking for

With this defined, it is possible to use the TAB key to navigate between the WPF controls on a Win32 window.

Here is the MFC demo application that you can try: Mfc-Wpf Tabbing (1302).

, , , , , Hits for this post: 54810 .

Alchemy 2.0

Alchemy 2.0 brings a modified layout, a set of 44 new elements (to a total of 444), hints, and translation to Hebrew.

The most reported bug for Alchemy so far has been the layout mess on small resolution systems, such as netbooks. It wasn’t a bug actually, but a feature. The application required a higher resolution, that how it was designed in the first place. The new version can run on netbooks too, but the minimum resolution is 1024×600. In order to support these small resolutions the layout was slightly modified so that it looks the same whether you use a lower or a higher screen resolution. Here is a screenshot from a netbook with 1024×600.

The following changes were done to the interface:

  • The buttons where put on top of the right panel
  • The trash icon where you could drag elements was removed and replaced with a button that when clicked removes all the elements from the desktop. Removing a single or only some elements is still possible by holding the CTRL key and selecting them with the mouse. Then press the DELETE key.
  • Hints are displayed on top of the window on the left and center panes. They are cycled every 15 seconds.
  • Displaying the total play time is enabled by default; it can be disabled from the Settings page.

A list of 44 new elements have been added to the game. The total is now 444. The list of new elements is:

Ambulance Liverpool
American football Lobster
Arsenal Manchester United
Audi Mercedes
Big Ben Monument
BMW Movie
C3P0 Music
Camel Nissan
Camera Oscar
Chelsea Picture
Colosseum Playcards
Cricket R2D2
Eiffel Tower Renault
Ferrari Rugby
Ford Sound
Formula 1 Sport
Guitar StarWars
Guitar hero Statue
Gymnastics Table tennis
Hockey Taj Mahal
Jellyfish Theater
Liberty Statue Toyota

The list with all the elements is available here.

The new version is also available in Hebrew. The total number of supported languages other than English is now 10. I want to thank again to all the volunteers that helped translating Alchemy to other languages. You can find their names in the Credits window. If anyone wants to help translating Alchemy to another language please drop a comment so I can contact you.

Download the latest version of the game from this page.

, , Hits for this post: 46616 .

Alchemy 1.7 brings a set of 20 new elements (tot a total of 400), allows you to display a timer with the total elapsed play time and is available in French.

The 20 new elements are:

Alcoholic Mirror
Ashtray Peat
Ball Rubber
Caramel Samurai
Clock ScotchWhiskey
Firefighter Scotland
Firefly Sugar
Football SugarCane
Juice SwissArmyKnife
LightningRod Tropics

The complete list of elements is available here.

Starting with version 1.7 you can display the total elapsed time since the beginning of the game. This can be enabled from the Settings page (in the More window) by checking the Display Timer option. However, if you already played Alchemy, the timer will only show the time you spent starting with version 1.7. The timer is reset only when you reset the game progress and start from scratch.

In addition the game is now available in French. If you want to help translating Alchemy to your language, please drop a comment so I can contact you.

Download the latest game version from here.

, , , Hits for this post: 48171 .

Alchemy 1.5 brings a set of new elements (focused on countries), a reorganization of parts of the user interface, translation to new languages and some new features requested by the users.

New elements
30 new elements have been added in version 1.5. Most of them are countries.

The list of new elements is:

Antarctica Germany Norway
Australia Iceland Romania
Brazil India Russia
Canada Italy Saudi Arabia
China Japan Sauna
Czech Republic Kangaroo Somalia
Dracula Karel Čapek South Africa
Egypt Mexico Switzerland
Finland Napoleon UK
France Netherlands USA

You can find the entire list of elements for the latest version here.

Changes to the User Interface
You can find the description of UI for the latest version here. On short:

  • Wiki button is back
  • Cheats button was removed and the Cheats window was moved to another place
  • Language button was replaced with button More; this opens a new window that allows you to:
    • saved and load your progress to a specific file, other than the default one; also reset your current progress
    • select the language
    • select various user specific settings
    • see the list of all available elements
    • see a list of those that helped translating Alchemy to other languages

New Features
The new features are disabled by default, and can be enabled from More > Settings. They are stored in the same file with the progress, so when you load from another file it changes to the settings stored in that file.

Combine only new prevents you from making already unlocked combinations over and over again. With this feature set, each combination can only be made once.

Tap to combine allows you to combine elements without dragging one over the other. You select the first element, and then the second, and if they make a combination, you get the result automatically. When you tap on an element, you can see a selection mark around the icon.

New Languages
Alchemy 1.5 is available in the following new languages:

  • Portuguese: translated by Bruno Silva
  • Czech: translated by Lukas Juda (LKJ)

Thank you all that helped with the translation, and if anyone wants to translate to another language please drop a comment so I can contact you.

The latest version is available for download here.

UPDATE: due to some problems with the Dutch and Czech translations I had to release a quick fix. Latest update is 1.5.2.

, , Hits for this post: 42980 .

Alchemy 1.3 is the latest update of Alchemy for Windows that brings 50 new exciting elements (taking the total to 350) and new features such as hints. The new elements in this release are focused on games; they include games such as Starcraft, Warcraft, Need For Speed, Tomb Rider, Resident Evil, characters such as Mario, Luigi, Yoshi, Jim Raynor, Zeratul, Queen of Blades, Lich King, and the races Zerg, Protoss, Terran, Fire Elemental.

Alchemy 1.3 new elements

The new elements are:

Aluminium Phoenix
Ant Protoss
Boo mushroom Queen of Blades
Computer game Resident Evil
Diet Robot
Easter egg Rust
Faberge egg Salamander
Fire elemental Sniper
Frog Spinning wheel
Infestation Starcraft
Insects Sushi
Jim Raynor Team
King Termite
Lara Croft Terran
Leach Tomb Raider
Lich King Undead
Lighthouse Vinegar
Luigi Vulture
Mantis Warcraft
Mario Weevil
Mosquito Yarn
Need for Speed Yoshi
Obesity Yoshi egg
OneUP Zeratul
Paint Zerg

You can find the list with all the 350 elements in Alchemy 1.3 here.

One new cool feature is the availability of hints. Press the new Hints button and a window pops-up displaying one possible element you can create, indicating also one of the two elements used to create it. To close the hints window, just click anywhere on it.

Another feature available in version 1.3 is adding elements to the desktop area by double clicking on them in the unlocked elements list. Terminal elements cannot be added to the desktop.

Note: if you already played Alchemy, just replace the old executable with the new one. Don’t delete the user settings file having your account name and extension .aus, or you loose the elements and combinations you unlocked so far.

Download the latest version from here.

, , Hits for this post: 60929 .

Alchemy 1.1 is the first update of Alchemy. It features 50 new cool elements and fixes a problem with the three elements (Bread, Hourglass and Snow) that were marked as terminals though they were required for making other elements. Combinations and elements are now verified formally so that they can all be resolved.

The list of the 50 new elements is:

Anubis Cemetery Jungle Pilot Sick
Avian flu Chariot Jungle Book Pirate Soap
Bacon Fat Kamasutra Pirate ship Submarine
Bar Feather Love Pyramid Swine flu
Bat Frankenstein McDonalds Quetzalcoatl Treasure
Batman Grave Mummy Robin Hood Twilight Saga
Berry Hen coop Museum Sailboat Vampire
Blood Hero Pharaoh Sandwich Werewolf
Captain Hospital Pig Sex Zombie
Captain Nemo Island Pillow Sex and the City Zoo

The entire list of elements is available here.

Note: if you already played Alchemy, just replace the old executable with the new one. Don’t delete the user settings file having your account name and extension .aus, or you loose the elements and combinations you unlocked so far.

Update: Download the latest version from here.

, , Hits for this post: 41926 .

Alchemy for Windows

I have played recently a great game on Android, called Alchemy, created by Andrey Zaikin. You start with four basic elements, Fire, Water, Air and Earth and you can combine them to get more and more elements. The game was so catching that after finishing it I decided to write my own version for Windows. I chose WPF because I wanted to learn it and because I realized the stuff I wanted to create was too hard to do in MFC. This is my first real application in WPF, and what you see is the result of 4 days of work; in MFC it could have been 4 months, I believe.

You start with the four basic elements: air, earth, fire and water. You can combine them by dragging onto each other on the central area of the window, “the desktop”. When new elements are created they are added to one of the two lists from the left area. The top list has elements that can be combined again. The bottom list contains terminal elements, i.e. elements that can no longer be combined. You can drag elements from the non-terminals list back to the desktop area, but not from the terminals list.

You can quickly bring onto the desktop the four basic elements by double clicking on an empty area of it. Double clicking on an element from the desktop creates a duplicate of it. You can remove an element from the desktop by dragging it over the trash can icon. You can remove all the elements from the desktop by double clicking on the trash can.

When the number of elements gets too big scrolling through the list might be cumbersome. You can use the search textbox to filter the elements in the list. As you type only the elements that contain the typed text are displayed. It you press the X button of the textbox or clear its content, the list displays again all the unlocked elements.

On the right area of the window you find a help pane. When you select an element from one of the two lists on the left side, you can see a list of all the unlocked combinations in which the elements appears (either as input or output).

There are also several buttons: Cheat, Wikipedia, Help and About. Button Cheat opens a new window that displays the list of all available elements. So if you get stuck and don’t know what elements are left to discover you can cheat and see the list.

Button Wikipedia starts a search on Wikipedia for the currently selected element. Buttons Help and About display information about the game.

Note that your game progress is saved when you close the game and loaded when you start again. The information is stored in a file with your Windows user name and extension .aus. Don’t delete the file or you lose your game progress.

Here is the alphabetical list of all the 210 elements available in version 1.0:

Air Cochineal Gunpowder Ozone Soldier
Airplane Coffin Hippopotamus Panda Star
Alcohol Combustion engine Hourglass Paper Starfish
Algae Computer House Pearl Steam
Arable Concrete Hunter Penguin Steam engine
Arm Continent Hut Penicillin Steamer
Ash Corpse Hydrogen Perfume Stone
Assassin Country Ice Petroleum Storm
Bacteria Darth Vader Jedi Pie Sulfur
Barbeque Desert Kerogen Pinocchio Sun
Beach Diamond Knife Pizza Swamp
Bear Dinosaur Lava Planet Tequila
Beast Dough Library Plankton The Beatles
Beer Dragon Lichen Plesiosaur Thunderstorm
Beetle Dragonfly Life Poison Tiger
Bicycle Dust Light Poisoned weapon Time
Bird Earth Lightbulb Polar Bear Tom and Jerry
Bitumen Egg Lightsaber Pressure Tool
Boat Electricity Lime Pterosaur Tornado
Boiler Energy Limestone Radar Tortoise
Book Fern Livestock Radio Transistor
Bread Fire Lizard Rain Tree
Brick Firearm Locomotive Rainbow Turtle
Butterfly Fish Man Sand Uncut diamond
Cactus Fisherman Manure Santa claus Universe
Car Flour Meat Scarab Vodka
Carbon dioxide Flower Metal Scientist Volcano
Carmine Flu Milk Scissors Wagon
Cat Fly Mite Scorpion Warrior
Caviar Fondue Mold Seed Water
Cement Forest Monkey Shark Watermelon
Cheese Fossil Moon Shell Whale
Chicken Fruit Moss Silicon Wheat
Chip Fugu Motorboat Sith Wheel
Christmas tree Galaxy Motorcycle Sky Wind
City Gasoline Mouse Skyscraper Wine
Clay Geyser Mud Snail Wood
Cloth Ghost Mushroom Snake Wooden ship
Clothing Glass Ocean Snow Wool
Cloud Grape Old man Snowman Worm
Coal Grass Omelette Soda water Yeast
Coca cola Grove Oxygen Solar system Yogurt

Note: In order to run the game you need .NET framework 3.5 SP1.

Stay tuned, updates with more elements are coming!

Update: Download the latest version from here.

, , Hits for this post: 208861 .

When you create a WPF application, the start-up window is by default one from the same project (by default called Window1.xaml).

But what if you want to use a window from another project (class library)? The pack URI scheme, used by WPF, allows you to identify and load files from:

  • the current assembly
  • a referenced assembly
  • a location relative to an assembly
  • the site of origin for the application

The format of the pack URI is pack://authority/path. The authority identifies the type of package and the path the location of a part inside a package. There are two authorities supported by WPF:

  • application:/// identifies application data files (known at compile time)
  • siteoforigin:/// identifies site of origin files

To use resource files from a referenced assembly you need to use the application:/// authority, and the path must have the form AssemblyShortName[;Version][;PublicKey];component/Path. Version and PublicKey are optional.

Let’s say you want to use a XAML called SampleWindow.xaml from a referenced assembly called WpfDemoLib. The App.xaml file should look like this:

You can learn more about pack URIs in WPF from MSDN.

, , , , Hits for this post: 49386 .

A few days ago, Microsoft, through Jason Zander, General Manager of Visual Studio, has revealed the new look of Visual Studio 2010 at the VSLive conference. Several screenshots and description of the new look you can find on Zander’s blog.

The new editor is using WPF and makes extensive usage of .NET 4.0. Here is a screenshot.

Visual Studio 2010 new WPF look

One of the important new features is support for multiple monitors. One can now put code or designer windows onto multiple monitors.

The New Project dialog allows you to view online templates and provides search options. Moreover there is an Extension Manager that allows you to search for online templates and tools, like add-ins or macros and install them into Visual Studio.

Other features offer support for working with multiple UML digrams and will allow arhitects to enforce the intended architecture. As Doug Holland explains,

When a developer checks in code within Visual Studio 2010 to the Team Foundation Server the developers code will be parsed to ensure that the developers code complies with the layer diagram. Within the layer diagram, for example, architects can prescribe that the UI code must communicate with the business layer and not directly with the data layer. If developers use types from the data layer within the UI layer then the checkin will not be allowed to proceed.

I think that will be a quite cool feature, and I’m looking forward to testing that.

Here you can read more:

, , Hits for this post: 34266 .