Avalon with C++/CLI – what are your options?

As of today (Feb CTP), Visual C++ projects cannot have XAML in them as C# and VB projects can. Of course, this does not mean that you cannot target Avalon using C++, and if you have read my previous blog entries, you’d have seen a couple of ways how that can be done. To put things in the right perspective, let’s see what options we have and their pros and cons.

  • 100% procedural code – This would allow you to develop Avalon apps with just VC++ and no other tool. Disadvantages would be a lack of UI-Logic separation, unsuitability for designing complex UIs, and increased lines of code. Advantages are you can use C++, and needn’t depend on VC# or any other tool.
  • C++ code dynamically loading XAML – You still stay within VC++ and are not dependent on other tools. You also achieve UI-Logic separation, because the UI stuff is in the XAML. But your apps would have loosely distributed XAML file dependencies, and any XAML corruption would mean trouble. And while you have reduced LOC, you still need to write code to wire the XAML elements with control variables.
  • Put the XAML in C#, derive a class in C++/CLI – This is a pretty decent option right now. There is full UI-Logic separation, and you can use Cider to design your XAML. The elements are wired to your code by the compiler and LOC is further reduced. Disadvantage is the dependency on a temporary C# project to create the XAML, and the need to put that in a DLL.

Of course, in future, if direct support for XAML is added to VC++ (as I believe it will), then that’d be our best option. But until then, we are not out of the game, which is a good thing I say 🙂


Avalon – The end of HWND voyeurism!

One fundamental aspect about Avalon controls is that they are not native HWND based controls, such as the ones you have been used to with Win32 API programming or with Windows Forms (which merely wraps the API). So if you have an Avalon window with a bunch of controls on it (say a ListBox and a couple of Buttons), none of them will have an HWND , because an Avalon control does not map to a native Windows control. If you use Spy++, you’ll see just a single HWND based window (the top level window) which hosts the Avalon window. Of course, there are possible ways to enumerate the child controls in an Avalon window using the WPF API, but Spy++, which had been the Number-1 window spying tool for a decade will either have to be abandoned or re-written to handle Avalon controls. Can you imagine not being able to PostMessage whatever you wanted to a control in a window in some other application running on your desktop? Coding is going to change – in many more ways than I had imagined!

Dynamically load a Xaml file from a C++ app

While it’s an absolute tragedy that C++ does not directly support compiled Xaml, you can use Xaml dynamically from a C++ Avalon app using XamlReader::Load. Let me show you how to do that, using a simple example. You can create your Xaml file, either using a text editor or using a temporary dummy C# or VB project.

  <Canvas Background="#FF008000">
    <TextBox HorizontalAlignment="Left"
             Width="240" Height="30"
             Name="mTextBox" />
    <Button  HorizontalAlignment="Left"
             Width="75" Height="23"
             Canvas.Top="45">Set Title</Button>

Now here’s the C++ code that will load this Xaml, show the window, and also hook events to the member controls. The code is mostly self-explanatory if you understand basic .NET event handling.

ref struct EventHelper
    static void OnBtnClick(Object^ sender, RoutedEventArgs^ e)
        Window^ mainwnd = Application::Current->MainWindow;
        TextBox^ txtbox = (TextBox^)mainwnd->FindName("mTextBox");
        mainwnd->Title = txtbox->Text;

int main(array<System::String^>^args)
    Stream^ st = File::OpenRead(
    Window^ mainwnd = (Window^)XamlReader::Load(st);
    mainwnd->Height = 400;
    mainwnd->Width = 600;
    mainwnd->Title = "Dynamically load Xaml";
    //FindName will find the element with the specified identifier
    Button^ btn = (Button^)mainwnd->FindName("mButton");
    btn->Click += gcnew RoutedEventHandler(&EventHelper::OnBtnClick);
    return (gcnew Application())->Run(mainwnd);

This Avalon stuff is pretty powerful I can tell you. Expect more entries as I figure out more stuff :nerd:

Writing a simple Avalon app with C++/CLI

You cannot use XAML with C++/CLI, so you’ll have to hand-code your UI, as of now anyway. Anyway, here’s what you need to do to write a simple app.

Step 1

Generate a new C++/CLI project, set the subsystem to Windows, set the entry point to main, and add the following references :

  • System (if not already present)
  • PresentationCore
  • PresentationFramework
  • WindowsBase

Step 2

Add the following using namespace declarations to your cpp file :

using namespace System;
using namespace System::Windows;

Step 3

Here’s your main method :

int main(array<System::String^>^args)
    return (gcnew Application())->Run(gcnew Window());

That’s all. Compile and run your app to see your first Avalon window in C++/CLI.

The SHCreateDirectoryEx API function

Very frequently in the forums, someone posts a question asking for a function that will create a full directory path for them. For example, they may want to create c:\a\b\c\d\e\f with one call, where the intermediate folders may not exist. The answer, if you are on Win 2000 or later, is to use the SHCreateDirectoryEx function that’ll do this for you. Here’s some sample code :

    _T("d:\\abc\\def\\ghi\\nish"), NULL);

It’s a really useful API function, just not that well known. Anyway this blog entry will serve as a link which I’ll point to, if I see this question popping up in the forums again.

A near heart attack!

On the 20th of February, 2006, I woke up at 4:45 AM with an agonizing pain in my chest, or to be more precise, the upper left area of my chest. I couldn’t even breathe properly, it was hard to even move my body, and I panicked thinking that I was having a heart attack. Smitha got me some hot coffee, and though it was a struggle to drink it, I somehow managed to gulp it in, though it didn’t really help at all. I googled for heart attack symptoms, and from what information I got, I was more convinced that this was a heart attack. My left shoulder was also beginning to ache, and this was another symptom for a subsequent heart attack or cardiac arrest. I thought I’d ask on the Code Project and started a thread on this, and asked people if they thought I was having a slow heart attack, and most people replied saying that it sounded serious, and that I should go to a hospital as early as possible.

By then, it was about 7 AM, and the pain wasn’t stopping. I suddenly realized that, I might only have a couple of hours more to live, and then all of a sudden, I started worrying about Smitha. If I was going to die that day, I began to ponder over how she would manage. I started to get her to memorize our bank pin numbers and passwords, as I wanted to make sure she’d be able to access enough money to get back to India on her own. Or at least live on her own for a while in Canada. I also thought we should go to work, so that if I did die of a heart attack, someone else would be there to help, rather than stay at home with just her, and she didn’t even have a Canadian driver’s license. As to why I didn’t go to a doctor, we don’t have health coverage yet in Canada, it only starts next month, and I wasn’t sure I’d be able to afford medical help. I was also worried that if I died that day, and wasted money by paying the doctor (or the hospital), that’d be even lesser money for Smitha to go back to India. I also started regretting not taking care of my diet, and eating all sorts of junk food, and not bothering to eat well when I consumed alcohol. I was disgusted with myself for not even spending an hour at the gym after taking membership, and spending close to a 100 bucks on workout clothes and a gym bag.

Right now, looking back at my actions and thought processes, it seems amazingly hilarious, but it wasn’t remotely funny at that time. There I was, nearly sure I was going to die, and worried to death about Smitha. There were moments when I wished I could see my family (in India) one last time, or at least speak with them, but I was too weak to even make a phone call. Anyway we drove to work, and it was a struggle as I had to strain myself to the maximum to keep myself from falling on the steering wheel. We reached work and Chris spoke with me about this, and asked me if it hurt more if I expanded my chest, and I tried that and it sure did hurt more. He smiled and said that I probably sprained a muscle there, and that he’s had that numerous times before. That made me feel a lot better, and over the day the pain did decrease a little, though it kept at a throbbing pace all the time, which was mighty worrying.

On our way home from work, I had my Blood Pressure taken, and it was normal. I then called a friend of mine (from Toronto) who was a Doctor in India (though she cannot practice in Canada until she gets the Canadian medical degree too), and after listening to my symptoms, she laughed and said it was only a chest muscle spasm. Apparently, I was overworking and putting too much strain on my body (I work on a computer 80-90 hours a week, counting time at home as well as at work), and this apparently affected my digestion, resulted in acidity, and started causing irritation to the chest regions, and thereby resulting in a muscle spasm – apparently muscles enjoy doing this spasm thing when they are irritated. In fact, Deepa (my Doctor friend) told me that this is pretty common, and is kind of similar to an anxiety attack, except I didn’t really have an anxiety attack. She asked me to cut down on the spicy food, and to take some anti-acidity tablets, which I did. It’s now 10 days later, and since Sunday, I’ve completely recovered from the chest pain.

I know this sounds ridiculous, like one of those things that Johnny Bravo or Daffy Duck would end up doing, but I am posting this here for posterity so that I’ll be more careful about my health and diet in future. The worst part of thinking you are going to die is worrying about how everyone who loves you will take it. Alright, that’s it, I am still alive, healthy, happy, writing, coding, and blogging, and don’t any of you dare poke fun at me over this, the next time we meet!

Article – A modal dialog that fades the background to gray-scale

I actually published that last week, but forgot to write about it on my blog since I was engrossed in some other issues – which I’ll blog about soon. Anyway, DimmerDialog is a .NET class I wrote, that shows a modal dialog which grays out the rest of the background, just like the Windows XP Shutdown dialog. This can be used when your application needs to show a very important message box or form that requires immediate user attention, though whether that’s good etiquette or not is up to you to decide, or perhaps your client to decide.