Fernando Machado Píriz's Blog

Posts about digital transformation, enterprise architecture and related topics

Posts Tagged ‘Giving a Presentation

Give me a handle and I will move the Earth

with one comment

image

This post’s title paraphrases a saying attributed to Archimedes, who is said to have remarked of lever “Give me a place to stand on, and I will move the Earth”.

For people like me who started developing Windows applications a long time ago, handles were the entry door to almost any resource through Win32 API. Do you want to close or minimize a window? You need that window handle. Do you want to write some text into a window client area? You need the font handle, the device context handle, and the window handle. And so on.

Fortunately, in actual .NET Framework times, almost no one cares about using handles, nor cares about knowing what they are. The .NET Framework hides the complexity of handling Windows resources through the Win32 API, and with that, it also hides the handles.

However, once in a while, there appear some problems for which the only solution is to get a handle. Here is an example.

One of the features of the Giving a Presentation demo application is the ability to hide desktop icons during a presentation, showing them back again when the presentation ends. While developing thsi feature, I unsuccessfully searched for a way to do that. As far as I could found, there is no public API function to do it; and most hacks available on the web -for example this one– use handles and Win32 API function calls, but does not work correctly: they disable the entire desktop, not only its icons; as a consequence, the desktop’s pop up menu disappears.

Speaking about desktop’s popup menu, what I needed was a feature like the one in the Show desktop icons command.

image

Then it was when the old knowledge about handles and the like became useful again. I knew that this command ended sooner or later being transformed into a WM_COMMAND sent to the desktop. What I needed to emulate this behavior was to know the arguments of the WM_COMMAND message and –as you can imagine- the desktop handle. Once I get this information, I could send the same WM_COMMAND to the desktop. The desktop would not distinguish between a message sent by the menu command or by my program, so it should handle it in the same way.

For both two things I used an old tool still included in Visual Studio installation: Spy++. This tool allow finding a particular window, and among other things, look at the messages it receives. The following picture show the Spy++ windows list node corresponding to the desktop. Please note that desktop is a window of the SHELLDLL_DefView class; we will see later how this information is used.

clip_image003

The following image shows the messages received by this window when command Show desktop icons is executed. Please not the command ID 29698 of the WM_COMMAND message; we will also see later how to use this information.

clip_image004

The function to hide or show desktop icons finally gets something like this:

/// <summary>
/// Toggles desktop icons visibility by sending a low level command to desktop window in the same way as the popup menu "Show desktop  
/// icons" does. Use <code>AreDesktopIconsVisible</code> to get current desktop icons visibility status.  
/// </summary>  
private static void ToggleDesktopIconsVisibility()  
{  
    IntPtr defaultViewHandle = FindShellWindow();
    UIntPtr resultArgument; 
    IntPtr returnValue = NativeMethods.SendMessageTimeout(  
        defaultViewHandle,  
        NativeMethods.WM_COMMAND,  
        new IntPtr(29698),  
        IntPtr.Zero,  
        NativeMethods.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,  
        1000,   
       out resultArgument);
} 

The NativeMethods class contains all the functions and constants imported from Win32 API; code is not shown here due to simplicity, but you can download it from CodePlex. The function SendMessageTimeout is used to send the WM_COMMAND with ID 29698 to the window whose handle was obtained with the FindShellWindow function.

On the other side, the FindShellWindow function finds and returns the desktop handle, strictlyspeaking, the handle to the window containing desktop icons, whose class is SHELLDLL_DefView. Finding this window was not easy. Due to unknown reasons, in certain systems the window is in some place in the windows’ hierarchy, but in other systems is in another place – both system being Window 7 RTM 32 bits. Because of this, the Giving a Presentation feature to hide and show desktop icons, did not work in every situations. I should thanks to my MVP coleague Elías Mereb for his help to test different candidate solutions until finding the good one.

/// <summary>
/// Called by EnumWindows. Sets <code>shellWindowHandle</code> if a window with class "SHELLDLL_DefView" is found during enumeration.
/// </summary>
/// <param name="handle">The handle of the window being enumerated.</param>
/// <param name="param">The argument passed to <code>EnumWindowsProc</code>; not used in this application.</param>
/// <returns>Allways returns 1.</returns>
private static int EnumWindowsProc(IntPtr handle, int param)
{
    try
    {
        IntPtr foundHandle = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "SHELLDLL_DefView", null);
        if (!foundHandle.Equals(IntPtr.Zero))
        {
            shellWindowHandle = foundHandle;
            return 0;
        }
    }
    catch
    {
        // Intentionally left blank
    }

    return 1;
}

/// <summary>
/// Finds the window containing desktop icons.
/// </summary>
/// <returns>The handle of the window.</returns>
private static IntPtr FindShellWindow()
{
    IntPtr progmanHandle;
    IntPtr defaultViewHandle = IntPtr.Zero;
    IntPtr workerWHandle;
    int errorCode = NativeMethods.ERROR_SUCCESS;

    // Try the easy way first. "SHELLDLL_DefView" is a child window of "Progman".
    progmanHandle = NativeMethods.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Progman", null);

    if (!progmanHandle.Equals(IntPtr.Zero))
    {
        defaultViewHandle = NativeMethods.FindWindowEx(progmanHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
        errorCode = Marshal.GetLastWin32Error();
    }

    if (!defaultViewHandle.Equals(IntPtr.Zero))
    {
        return defaultViewHandle;
    }
    else if (errorCode != NativeMethods.ERROR_SUCCESS)
    {
        Marshal.ThrowExceptionForHR(errorCode);
    }

    // Try the not so easy way then. In some systems "SHELLDLL_DefView" is a child of "WorkerW".
    errorCode = NativeMethods.ERROR_SUCCESS;
    workerWHandle = NativeMethods.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "WorkerW", null);
    Debug.WriteLine("FindShellWindow.workerWHandle: {0}", workerWHandle);

    if (!workerWHandle.Equals(IntPtr.Zero))
    {
        defaultViewHandle = NativeMethods.FindWindowEx(workerWHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
        errorCode = Marshal.GetLastWin32Error();
    }

    if (!defaultViewHandle.Equals(IntPtr.Zero))
    {
        return defaultViewHandle;
    }
    else if (errorCode != NativeMethods.ERROR_SUCCESS)
    {
        Marshal.ThrowExceptionForHR(errorCode);
    }

    shellWindowHandle = IntPtr.Zero;

    // Try the hard way. In some systems "SHELLDLL_DefView" is a child or a child of "Progman".
    if (NativeMethods.EnumWindows(EnumWindowsProc, progmanHandle) == 0)
    {
        errorCode = Marshal.GetLastWin32Error();
        if (errorCode != NativeMethods.ERROR_SUCCESS)
        {
            Marshal.ThrowExceptionForHR(errorCode);
        }
    }

    // Try the even more harder way. Just in case "SHELLDLL_DefView" is in another desktop.
    if (shellWindowHandle.Equals(IntPtr.Zero))
    {
        if (NativeMethods.EnumDesktopWindows(IntPtr.Zero, EnumWindowsProc, progmanHandle))
        {
            errorCode = Marshal.GetLastWin32Error();
            if (errorCode != NativeMethods.ERROR_SUCCESS)
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
        }
    }

    return shellWindowHandle;
}

In certain situations, even in the .NET Framework era, it is still useful to get a handle: give me one, and I will move the Earth. Or at least, I will hide and show desktop icons. See you later.

Written by fernandomachadopiriz

August 9, 2010 at 2:46 pm

Posted in C# 4.0

Tagged with

The new Visualization and Modeling Feature Pack allows generating UML diagrams from code and vice versa

with one comment

Microsoft recently published the Visualization and Modeling Feature Pack for Visual Studio 2010. Download is available for MSDN subscribers here. The following (longly awaited) features are included:

  • Generate code from UML class diagrams.
  • Create UML class diagrams from code.
  • Import UML class, sequence, and use case elements from XMI 2.1 files.
  • Create and view links from work items to model elements.
  • Generate dependency graphs for ASP.NET Web, C, and C++ projects.
  • Create and validate layer diagrams for C and C++ code.
  • Write custom code to create, modify, and validate layer diagrams.

The following UML class diagram from Giving a Presentation was created using the Visualization and Modeling Feature Pack in just a couple of minutes:

ClassDiagram

Do you recognize how the Model View View Model pattern was used? It is easy from the diagram, is not it?

Written by fernandomachadopiriz

June 16, 2010 at 9:15 pm

A simple introduction to the Model View ViewModel pattern for building Silverlight and Windows Presentation Foundation applications

with 5 comments

Some time ago I was looking for a simple introduction to the Model View ViewModel pattern (also known as MVVM) and all the samples I was able to find were a bit complicated to my taste. I this post I will try to present you the MVVM pattern using the simplest possible example, focusing just on the key MVVM concepts. In other posts I will deep dive on other closely related concepts, but let us start with the basics.

MVVM is a successor of another well-known and very successful pattern so called Model View Controller (MVC). MVC was born (like many other well-known and successful patterns) in the Smalltalk world more than thirty years ago. Using MVC the application is composed by three kinds of objects, with very clear and differentiated responsibilities:

  • The model. Usually there is only one model per application. The model is responsible for all application’s data and related business logic.
  • The view or views. One or more representations for the end user of the application’s model. The view is responsible for showing data to end users and for allowing end users to manipulate application’s data.
  • The controller or controllers. Usually there is one controller per view, although it is not uncommon to see one controller per domain entity controlling multiple views. The controller is responsible for transferring data from the model to the associated view and vice versa. It is also responsible for implementing view’s behavior to respond to user actions.

image 

With MVC each type of object is responsible for just one thing, which simplifies developing, understanding and testing the code. In addition, it is easy to replace views, or to have more than one view of the same data.

In the case of Silverlight and Windows Presentation Foundation (SL/WPF) applications, the .NET framework provides the ability to use binding to transfer data to and from the view, so the controller is only responsible for implementing view’s behavior. In this case, the controller is called view model, leading to the MVVM pattern:

  • The model. Same as with MVC.
  • The view or views. Also the same as with MVC. Views are SL/WPF windows.
  • The view model. One view model per view. The view model is responsible for implementing view’s behavior to respond to user actions and for exposing model’s data in an “easy-to-bind” way to the view.

image

MVVC shares all of the benefits of MVC, but it has an additional benefit: the simplification resulting from using declarative binding to transfer data back and forth the view model to the view.

I will illustrate how MVVC works with an example. The code I will be using in this post comes from my sample application Giving a Presentation (although you are encouraged to download the installation file and the source code of Giving a Presentation from CodePlex, there is no need to do it in order to follow this post).

Giving a Presentation is a simple application to change certain setting while delivering a presentation, e.g., hide desktop icons, remove or replace desktop background, etc. Changes are reverted back when presentation ends.

The ability to change settings is provided by extensible parts and is not implemented in the application itself (more details in this post). So strictly speaking, the data Giving a Presentation deals with is just a boolean value indicating if the user is giving a presentation or not: the user sets the value on true when presentation starts, and set it back on false when presentation ends.

The model’s code is as follows. As promised, it is very simple; it has just a boolean property:

public class Model
{
    public bool GivingAPresentation { get; set; }
}

Here’s the view model’s code. It is also very simple. Like the model, it has a just a boolean property, whose value is get and set from an instance of the model.

public class MainViewModel
{
    private Model model;
    public bool GivingAPresentation
    {
        get { return model.GivingAPresentation; }
        set
        {
            model.GivingAPresentation = value;
        }
    }

    public MainViewModel()
    {
        this.model = new Model();
    }
}

The view (without any extensible part on it) looks like this:

image

The corresponding XAML code is:

<Window x:Class="GivingAPresentation.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:GivingAPresentation "
        Title="Giving a Presentation" Height="350" Width="525" Icon="/MvvmDemo;component/Images/Presentation.ico">
    <Window.Resources>
        <vm:MainViewModel x:Key="mainViewModel"/>
    </Window.Resources>
    <Grid>
        <CheckBox Content="I'm currently giving a presentation"
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,12,0,0"
                  IsChecked="{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}" />
    </Grid>
</Window>

Interestingly, there is no code behind for this view[1] (furthermore, I have deleted the file MainView.xaml.cs from the project, and obviously the solution compiles and the application runs perfectly). Do you wonder why? Because there is no need to have any code in view’s code behind class; view’s behavior is coded in the view model, not in the view, do you remember?

The view is connected with the view model in three steps. First, an xmlns attribute in the Window node is used to alias the GivingAPresentation namespace as vm with xmlns:vm=”clr-namespace:GivingAPresentation. Second, an instance of the view model is created in the Window.Resources node; the name of the instance is declared with x:Key=”mainViewModel”. And finally, the IsChecked property of the view’s check box is binded with view model’s GivingAPresentation property with IsChecked=”{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}”.

And that’s it. WPF/SL does the magic of getting check box’s state from view model’s property value, which in turn is taken from the corresponding model’s property value. WPF/SL also does the magic of setting view model’s property value whenever the user checks or unchecks the check box. The view model propagates property value change to the corresponding property in the model. Through this chain, a change in the view is reflected in the model.

This example is perhaps too basic, but it has all the key components of the MVVM pattern, and clearly shows the basis for implementing WPF/SL applications using that pattern.

What is next? There many things, very common in real world scenarios, not resolved at all in this very simple demo; for example:

  1. Not only the view, but probably other objects need to be aware of changes in view model’s properties values. That is where the INotifyPropertyChanged interface comes in to play. By firing a PropertyChanged event every time properties’ values change, other objects can react to these changes. It is worth to mention that those objects are not known by the view model, but will be notified anyway, thanks to the .NET Framework’s events infrastructure.
  2. It is very common for the view to ask its view model to execute certain actions. This can be achieved by the view model exposing commands, and the view binding control’s actions (like click) to those commands.
  3. It is also very common in real live applications to have interdependent views that need to communicate between them. To keep those views, and their associated view models, independent from each other, view models can use messages to communicate between them.
  4. Who creates who? In this simple demo the view declaratively creates the view model (in view’s XAML code), and the view model creates the model. In large applications, this approach is not always feasible, and you need other helper classes to manage objects creation.

These aspects are really not part of the MVVM pattern, but are actually needed to implement real world applications using WPF/SL; that is why you usually will see them covered together with the MVVM pattern in the literature. I plan to cover them in future posts, just to keep the MVVM basics, basic.

Hope you have enjoyed this explanation. Looking forward to see you soon. Bye.


[1] In this example. In Giving a Presentation’s real code, the view is responsible for presentation related tasks, like showing the notification icon when minimized for example, that requires code behind the view.

Written by fernandomachadopiriz

June 10, 2010 at 12:41 am

Do you usually give presentations? Check this out

with 13 comments

For end users: Giving a Presentation is a simple application to change certain setting while delivering a presentation, e.g., hide desktop icons, disable screensaver, close selected programs, etc. Changes are reverted back when presentation ends. Initially built to show how to use certain technologies, it turned out to be useful by itself.

Watch this video to see Giving a Presentation in action:

If you want to try Giving a Presentation for youself, you can download installation bits from Codeplex.

For developers: Giving a Presentation is a WPF application sample created in C# that I use when blogging about Managed Extensibility Framework, Dependency Injection and Inversion of Control, etc. It demonstrates how an extensible application can be built as a container of component parts.

In this sample application, the container is the main window, plus the tab control on it. The tab control has just a Default tab and an About tab. The Default tab is initially empty; it will be dynamically filled by component parts.

clip_image002

The About tab shows typical information about application version, etc.

clip_image003

Component parts need to fulfill three requisites:

  1. Should implement an interface GivingAPresentation.Common.Contract.
  2. Should the decorated with the System.ComponentModel.Composition’s Export attribute.
  3. Should be deployed in an assembly in the same folder as the container.

The Managed Extensibility Framework and the MainWindow of the application will do the rest. The former will load instances of all exported types implementing the mentioned required interface in a list. The later will take the instances in the list and add the controls to the appropriate tab in the control tab.

Until now, I have created three component parts, to solve some of the typical problems that appear when giving a presentation:

  • Hide desktop icons. Usually you place working documents in your desktop. Some of these documents are private and you don’t want your audience see them before you start delivering a presentation. Use this feature to hide your desktop icons during a presentation and unhide them at the end
  • Disable screen saver. You may have your screen saver configured to start after certain time of inactivity. If you spend some time in a single slide during a presentation, your screen saver can interrupt your presentation. Use this feature to disable your screen saver during a presentation and enable it back at the end.
  • Close programs. Some programs pop up notification messages, e.g., mail or instant messaging clients when messages arrive. Despite of the interruption, the content of the notification might be inappropriate to be seen by your audience during a presentation. Use this feature to close selected programs during a presentation and open them back at the end.

Watch this video to see how these parts effectively extend the container:

You can download the source code also from Codeplex.

Give it a try. Hate it? Love it? Let me know.