Category Archives

Setting the device brightness on Windows with WPF

.NET, Technical stuff, Windows 10, Windows 7, Windows 8, Work, WPF
2 Comments

I am working on a project which I can’t really detail, but one aspect caused me a few headaches. Finally I reached out to the Windows team at Microsoft and got great help from Katie Anderson who works on the brightness team. This was quite tricky, and we had to have a couple of roundtrips before we managed to find a way that worked.

Well, why?

In the application I am working on, it is necessary for the user to set the device brightness from the application itself. You might wonder why, because most Windows devices have hard keys to set the monitor brightness. For example on a Surface, you can use the Fn-Del and Fn-Backspace key combinations to alter the brightness of the screen. Or you can of course swipe from the right side and use the Brightness button to change the value in the Action Center.

However on that particular project, the user doesn’t have access to the keyboard, nor to the Action Center. This is a kind of kiosk scenario if you will where many of the Windows features are deactivated by policies, and no hard keyboard is provided. I had to find a way to do this programmatically.

First approach: Not so good

At first I thought I would have my application’s main window run in full screen and set a black Rectangle on top of everything, and change the Rectangle’s opacity in my code. That worked well but of course it wouldn’t work if other applications were in the foreground (yes, I forgot to mention, it’s a kiosk app which can start other apps and put them in the foreground…).

Second approach: Better but not great

OK, no problems I thought, let’s have my app open a modal full screen window which is always on top. I will then have this window made insensitive to touch or mouse clicks with the following code. Finally, this window will have the black Rectangle and be on top of everything all the time.

public static class WindowsServices
{
    private const int GwlExstyle = -20;
    private const int WsExTransparent = 0x00000020;

    public static void SetWindowExTransparent(IntPtr hwnd)
    {
        var extendedStyle = GetWindowLong(hwnd, GwlExstyle);
        SetWindowLong(hwnd, GwlExstyle, extendedStyle | WsExTransparent);
    }

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
}

This worked OK but somehow it was not satisfying. I really wanted to have a solution where my app would modify the actual device brightness. There are a few reasons why the client also wanted that, and so I started to investigate deeper. Unfortunately, Bing searches (and the equivalent Google searches) didn’t really return anything satisfactory.

Using Powershell

After searching a bit, I got a first clue that what I wanted to achieve was doable: You can query and modify the device brightness from Powershell with the following script:

CODE TO GET THE BRIGHTNESS INSTANCE

PS C:> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness

CODE TO SET THE BRIGHTNESS

PS C:\Users\lbugn> $monitor = Get-WmiObject -ns root/wmi -class wmiMonitorBrightNessMethods
PS C:\Users\lbugn> $monitor.WmiSetBrightness(50,10)

If you run these commands in Powershell, you will marvel at the result: Yes it does work and the screen’s brightness is modified. Great Scott, I am on the right track! The key to this is the WMI (Windows Management Interface) class WmiMonitorBrightness.

Converting to .NET

The next step was obvious: I needed to convert the Powershell script to some usable .NET code. Unfortunately, easier said than done. This is where I reached out to Microsoft for help and thankfully Katie really followed through and after a few iterations we got it to work.

First she used the WMI Code Creator tool to convert the Powershell script to .NET. I had no idea that such a tool existed, but then again I never had to dive so deep in the entrails of Windows. Unfortunately when running the code that the tool created (which I won’t post here to avoid confusion), I got some errors. One more roundtrip to Redmond (via email) and Katie found the way: The following code will indeed modify the brightness of the screen, yay!!

public static class WindowsServices
{
    private static ManagementObject _brightnessInstance;
    private static ManagementBaseObject _brightnessClass;

    static WindowsServices()
    {
        // Querying the Windows service to get the Brightness API.
        var searcher = new ManagementObjectSearcher(
            "root\\WMI", 
            "SELECT * FROM WmiMonitorBrightness");

        var results = searcher.Get();
        var resultEnum = results.GetEnumerator();
        resultEnum.MoveNext();
        _brightnessClass = resultEnum.Current;

        // We need to create an instance to use the Set method!
        var instanceName = (string)_brightnessClass["InstanceName"];
        _brightnessInstance = new ManagementObject(
            "root\\WMI",
            "WmiMonitorBrightnessMethods.InstanceName='" + instanceName + "'",
            null);
    }

    public static int GetDeviceCurrentBrightness()
    {
        // Getting the current value.
        var value = _brightnessClass.GetPropertyValue("CurrentBrightness");
        var valueString = value.ToString();
        return int.Parse(valueString); // Direct cast fails.
    }

    public static void SetDeviceBrightness(int newValue)
    {
        if (newValue < 0)
        {
            newValue = 0;
        }

        if (newValue > 100)
        {
            newValue = 100;
        }

        var inParams = _brightnessInstance.GetMethodParameters("WmiSetBrightness");
        inParams["Brightness"] = newValue;
        inParams["Timeout"] = 0;
        _brightnessInstance.InvokeMethod("WmiSetBrightness", inParams, null);
    }
}

I made a small sample here which gets the current value of the screen brightness and then increases it by 10% every time you click on a button. When you reach 100%, it goes back to zero on the next click. Simple enough, and does the trick.

I hope that this will be useful to a reader looking for the same feature. I’d love to be the first one to ever blog about this. I doubt that I am, and probably someone will point me to the article that I never found :) but seriously, I really couldn’t find any mention of something like that on the whole WWW.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook
 

My #XamarinEvolve talk is online for your viewing pleasure

.NET, IdentityMine, MVVM, Phone, Technical stuff, UX, Windows 8, Windows Phone, Work, Xamarin, XAML
5 Comments

20141022001

Update 13th January 2015: I updated the sample to the new Xamarin.iOS Unified APIs which are required for 64 bits support. See the related blog post here.

The Xamarin team did it! My talk (and all the other Xamarin Evolve talks) are available in video for your viewing pleasure.

Read the rest of this entry »

Announcing MVVM Light V5 for Windows and Xamarin

.NET, Blend, MVVM, Phone, Silverlight, Technical stuff, Visual Studio, Windows 8, Windows Phone, Work, WPF, Xamarin, XAML
53 Comments

Here at the Xamarin Evolve conference in Atlanta, I just announced the immediate availability of MVVM Light V5. This version runs on the following platforms:

  • Windows Presentation Foundation (3.5, 4, 4.5, 4.5.1)
  • Silverlight (4 and 5)
  • Windows Phone (7.1, 8, 8.1 Silverlight, 8.1 RT)
  • Windows Store (8, 8.1)
  • Xamarin Android
  • Xamarin iOS
  • Xamarin Forms

Read the rest of this entry »

MVVM Light Fundamentals, a Pluralsight course

.NET, Blend, MVVM, Pluralsight, Silverlight, Technical stuff, Windows 8, Windows Phone, Work, WPF, XAML
6 Comments

Today, my Pluralsight course “MVVM Light Fundamentals” was published. It is the achievement of a long road for me, the conclusion of an adventure that started more than a year ago with the awesome people at Pluralsight. I won’t talk too much about why it took me so long to create this course, let’s just say that creating videos is really a totally different business than book writing. I had to work a lot to find the right way to do things, and especially find ways to optimize the act of recording the video, which I can only do when I am not travelling. It took a while until I found the correct way to do things. Everyone says that the first course is horribly hard, and I can vouch for that. They also say that the next courses are much easier, and I hope I can prove this too :)

Read the rest of this entry »

MVVM Light V4.4 with Xamarin Android support

.NET, MVVM, Phone, Silverlight, Technical stuff, Windows 8, Windows Phone, Work, WPF, Xamarin
22 Comments

I just published MVVM Light V4.4 to Nuget. For now, this is only the “libraries only” package as I still have some testing to do on the full package as well as on the PCL package.

A “formal” list of changes can be seen here.

Possible breaking change

Let’s start with a possible breaking change. After much feedback “from the field”, I decided to change the names of the MVVM Light DLLs to remove the indication of the framework that they are built for. This might require you to update your XAML files accordingly. I am sorry if that causes you some effort, but I think it makes sense, considering that we are encouraged to share some XAML between the platforms (for example between WinStore and WinPhone), and the naming was breaking this.

Read the rest of this entry »

XAML Intellisense just got better

.NET, Blend, Build, Design, MVVM, Phone, Silverlight, Technical stuff, Visual Studio, Windows 8, Windows Phone, Work, WPF, XAML
2 Comments

With the latest Visual Studio Update 2 release candidate came a pretty wonderful surprise from the XAML tools team: Improved Intellisense when you use MVVM Light.

Short story

After you install the latest update to Visual Studio, you will notice the following effect:

Read the rest of this entry »

Deprecating the DialogMessage

.NET, MVVM, Phone, Silverlight, Technical stuff, Windows 8, Windows Phone, Work, WPF
14 Comments

One change you will notice when you install MVVM Light V4.3.31 is that I marked the DialogMessage class as Obsolete.

The DialogMessage class is one of the built in message classes in the MVVM Light Messaging namespace. When sent by the Messenger to a view element (Window, Page, etc), it carries information that can be used by the recipient to display a message to the user. It also has a callback to pass the result (OK, Cancel, etc) back to the caller for handling.

Read the rest of this entry »

Building a Universal Application for Windows Phone 8.1 and Windows 8.1 with MVVM Light

.NET, Blend, Build, MVVM, Phone, Silverlight, Technical stuff, Windows 8, Windows Phone, Work
47 Comments

In the previous article, we talked about the new Universal apps which can be created for Windows Phone 8.1 and Windows 8.1. This offers a nice way to structure your app in order to share as much code and other files (artwork, etc) as possible. It makes it easier than ever to create apps which target both the Windows Phone and the Windows RT devices like Surface.

The new concepts can be a little confusing and overwhelming at first, but practice will help a lot. In this article, we will see how a new Universal app can be created with MVVM Light support. That should be fun!

Creating the app and adding MVVM Light support

Let’s start by creating a new universal application:

Read the rest of this entry »

About Windows Phone 8.1 and universal apps

.NET, Build, MVVM, Phone, Silverlight, Technical stuff, UX, Windows 8, Windows Phone, Work
15 Comments

At the Build conference, Microsoft just released the new Windows Phone 8.1 “blue” SDK. Looking back in time, I think that it is one of the most significant changes to the Windows Phone framework since it was first released back then in 2010. First there is a wealth of new features and APIs, and there will be plenty of articles about that! Then there is a new architectural direction which will allow even more code sharing between Windows 8.1 and Windows Phone 8.1 than in the past! And soon for Xbox too.

Windows Phone 8.1 apps

When you install Visual Studio Update 2 which was just released as a release candidate (RC), you will see that there are now two ways to build Windows Phone applications. In 8.1, you can select a “Windows Phone 8.1″ application and a “Windows Phone Silverlight 8.1″ application. This post will explain some of the differences. There is also a “Universal Application” template, and we will also talk about that.

Read the rest of this entry »

Source code documentation for MVVM Light V4.2.30

.NET, MVVM, Phone, Silverlight, Technical stuff, Windows 8, Windows Phone, Work, WPF
No Comments

Not sure if you noticed but there is currently a LARGE effort around MVVM Light documentation. On one hand the Pluralsight course I have been working on for the past months is in the final stages of review now. Also, I have revamped and actualized the MVVM Light pages on my site as well as the Documentation page on Codeplex.

One thing that was still on my list is to publish the source code documentation. You might know that (or not), but the MVVM Light source code is documented in a pretty complete manner with XML documentation. There are here and there comments that are missing or incomplete, but for the most part it is pretty solid.

In order to make the usage of this inline documentation easier, I extracted it using Sandcastle. The source code documentation is now available as CHM (compiled HTML) documents as well as online HTML at the following location.

Read the rest of this entry »