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
 

Code and slides posted for my latest talks

.NET, Conferences, HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, UX, Windows 10, Work, Xamarin, XAML
No Comments

October and November have been quite busy with travel. I talked at a few occasions in some cool events and want to take a moment to share the code and slides below:

Xamarin Dev Day, Zurich, Switzerland

I love the concept of the Xamarin Dev Day. It’s a great way to reach out to local communities and have a day of fun teaching and training with Xamarin content. This year I took part to the Zurich, Switzerland occurrence. It definitely didn’t hurt that it was help in a very cool space, under a train viaduct in the previously industrial area of the city, which is these days a pretty cool place to live and work.

I held my talk titled “Building truly cross platform applications with Windows, Xamarin and MVVM Light” which comments on the fact that the so called “UWP” (Universal Windows Platform) applications are only for Windows (hence the W) and that if you want to target mobile iOS and Android devices, you need something more. Xamarin and MVVM Light are great solutions in this scenario, because they maximize the amount of code that can be shared, all the while increasing the testable surface of the application. You can find the code and slides at this page.

KC .NET User Group & Xamarin KC Dev, Kansas City, Missouri

You might have read that the company I joined in 2008 (IdentityMine) was acquired this year by a company based in Kansas City named Valorem Consulting. On November 1st and 2nd, I spent time at the head office to meet with a maximum of new colleagues. It was a nice stay in a city (and state) I had never visited before. In fact I even “visited” two states during that stay, because Kansas City is laid over Missouri and Kansas! Earlier on I had tweeted about me visiting KC, and the local .NET developer user group contacted me and asked if I wanted to speak at a user group meeting on that evening. Of course the answer was a resounding yes! And the best part is that the Xamarin KC user group also joined the fun for their first ever joint event. We had a great attendance with a full room of about 65 people, and a very nice interaction. After the event, a small group gathered at a local bar and we had pie and drinks (I had a root beer float, because why not). Excellent way to make new friends in a new city! I also held my talk “Building Truly Universal Applications with Windows, Xamarin and MVVM Light”.  You can find the slides and code here.

DevIntersection Europe, Haarlem, The Netherlands

Right after my return from the US (with the visit to Kansas City, a few days in the office in Seattle and then the MVP and Regional Directors Summit in Bellevue/Redmond), I had another short trip to the Netherlands. I spoke at the DevIntersection conference in Haarlem, a small city not far from Amsterdam. The location was superb, a convention center close to the historical center of the city, the hotel was great too (though the bed was wayyyyy too soft for me :) and the audience was very nice. It is definitely smaller than DevIntersection in the US (where they have events in Vegas and Orlando), but I had a good albeit small audience nonetheless and some great interactions with attendees and fellow speakers.

I spoke about the Windows 10 Universal Windows Platform, a dense session which contains information about creating a new UWP app; adapting the user interface to the various form factors, resolutions, orientations etc; porting classic windows applications to the Windows 10 ecosystem with the Desktop App Converter (also known as Centennial bridge); the Windows Continuum; and Microsoft HoloLens. Unfortunately because of unknown technical issues, I was not able to stream the HoloLens output to my phone nor to my Surface like I used to do. Unfortunately we ran out of time before I was able to solve the issue (which would probably have required restarting the HoloLens and the phone). I want to apologize to the audience for this technical glitch. I hope that the people who joined me later for a quick trial of the HoloLens were happy anyway, and that the others didn’t go back home with a bad image of this amazing technology :) I recorded a few videos showing the various demos I wanted to give, you can find all the material including code and slides on this page.

Thanks all for attending and happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

#Microsoft #Experiences in Paris: Code and slides

.NET, Conferences, HoloLens, MVVM, Technical stuff, Windows 10, Work, WPF, Xamarin, XAML
No Comments

Last week I had the pleasure of taking the TGV from Zurich to Paris, and after a quick 4 hours of comfortable travel, to make my way to the Porte Maillot and the Palais des Congrès.

TL;DR: All slides and source code is available from here.

A podcast

After a good night sleep I made my way to the speakers lounge and prepared the last steps for my talk. Then I took a moment to head to the meeting room where the Live Tiles podcast was being recorded. A band of podcasters got together and talked about the future of Microsoft. It was so nice to “see these familiar voices” in action. Even nicer when Christophe (Toss .NET) and Denis saw me and pulled me in to talk about HoloLens and our experiences with this device. You can hear the recording here, my contribution starts at 36:30.

My talk: Really universal apps with Xamarin and MVVM Light

My talk was titled (in French) “Construisons des applications vraiment universelles avec Windows, Xamarin and MVVM Light”. This favorite topic of mine shows how you can structure an application to share a maximum of code without any compromises. You can build healthy layers of Model and ViewModel, unit test them so you can feel secure about not breaking anything with future changes. Then you can build a thin layer of real native user interface for any supported framework with XAML or Xamarin (Windows Presentation Foundation, Windows 10 Universal, Xamarin.iOS, Xamarin.Android). And if you are in an enterprise scenario and looking for maximum productivity, you can also of course use Xamarin.Forms and render the same UI to all supported platforms.

The MVVM Light Toolkit assists you in these tasks, notably by providing a Data Binding framework for Xamarin.iOS and Xamarin.Android, as well as components that make it very easy to connect a list control to an ObservableCollection, with automatic refresh in case the collection changes. This open source toolkit is in it’s version 5.3, has been downloaded almost 1.7 million times and is even used by Microsoft to build parts of Windows 10.

I was really pleased when I headed to my conference room and saw a long queue in front of the entrance. I gave my talk to a standing room of about 270 people, and loved the interaction during and after the talk. A lot of very positive feedback, and we stayed and talked until the hostess kicked us out of the room :)

Thank you to everyone who came and made this a memorable moment. You will find all the details of the talk, the slides and the source code from this portal.

Some tea

Before I made my way to the Palais des Congrès, I took a pit stop at one of the most wonderful shops on Earth: the Mariage Frères tea store. This old fashioned store is stock full of amazing teas from all over the world. It’s a must-visit if you are a tea enthusiast or if you just want to spend a moment living in an atmosphere of luxury and pleasure.

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and code samples for VS Live Redmond

HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, Xamarin, XAML
No Comments

VS Live just took place in Redmond, and I had a great time. I had three sessions in one day, and I was really exhausted in the evening, but it was absolutely worth it. Speaking in Building 33 (the conference center on Microsoft campus) was an amazing experience. I have spent so many hours in this building, listening to amazing speakers of Microsoft and others, during MVP summits and other events… so really it was quite magical to be on the speaker side this time, in room St Helens.

vsliveredmond

Thanks to every one who came to my talks! I hope it was informative and useful, and that it encourages you to try those technologies and techniques.

Here are the pages for the talks I gave:

Windows Presentation Foundation (WPF) 4.6
Windows Presentation Foundation is what people are using to build real applications for the enterprise, the industry, the workplace, and for every situation where Windows 10 Universal isn’t quite ready yet. Far from being dead, WPF is 10 years old this year, and it’s still alive and kicking. It gives Universal Applications a run for their money. In this session, you’ll learn what is new in Windows Presentation Foundation, where it’s going in the future, and what you can achieve with WPF that Universal Application developers can only dream of. We’ll also see how these two roads cross and how existing WPF applications can be brought to Windows 10 using the Centennial bridge. Finally we’ll discover new features and tools recently implemented for WPF developers.

Windows 10 – The Universal Application: One App To Rule Them All?
Windows 10 and the Universal Windows Platform offer a lot of productivity and flexibility around targeting the broad set of devices that run Windows. As a developer, you have a lot of choice–from building a single binary that is identical on all devices, through to an app that adapts to the type of device and on to the point of building an entirely different app for each class of device. What’s the right thing to do? How should you think about building the “One App to Rule Them All?” What are the design and implementation trade-offs you need to consider? This session dives into these areas with a hands-on approach and shows what it really means to be building apps across families of Windows devices that have different capabilities. We will also talk about bridges (and especially the iOS Bridge to Windows 10), and new platforms such as Continuum and HoloLens (with live demos).

Building Truly Universal Applications with Windows 10, Xamarin and MVVM
With Windows 10 supporting an unprecedented number of platforms and form factors (from IOT to phones to tablets to laptops and desktops to XBOX and SurfaceHub, and even the new HoloGraphic computer HoloLens), the name ‘Windows 10 Universal application’ is fairly accurate. But to be honest, shouldn’t a truly Universal application run on Windows 7, iOS and Android devices too? Thankfully, this is possible thanks to a clever architecture pattern named Model-View-ViewModel, the .NET portable class libraries and the Xamarin frameworks. With these tools, we can structure an application so that most of the code is shared across all the platforms, and then build truly native UI that adapts without any compromises to the device it runs on. In this session, we will understand exactly how such universal applications are built. Laurent Bugnion, a XAML/C# expert, Microsoft and Xamarin MVP who started making universal applications before it was even a thing, will show you practical knowledge with a lot of demos. Come listen from the creator of the popular MVVM Light Toolkit how this powerful but simple library can be leveraged to help you target more users than you ever dreamed of!

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and sample code for my presentations at #VSLive Boston

.NET, Conferences, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, XAML
2 Comments

Thanks to everyone who came to my sessions at VSLive Boston. I had a great time. I hope it was informative and useful. I am aware that you take time out of your job to come and see us speak and I really hope that you found it worth your time.

I had two sessions:

Windows 10 – The Universal Application: One App To Rule Them All?

You can find the slides and sample code for this session here. This page also links to a video showing how Windows 10 Universal apps work on HoloLens!

Windows Presentation Foundation (WPF) 4.6

Here are the slides and sample code.

Thanks again for your warm welcome in Boston!! I even had some time to visit the city and had a blast in the historical places.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Back from Sweden! Slides and code for my #DevSum16 session

.NET, Conferences, HoloLens, Technical stuff, Universal Windows Platform UWP, Windows 10, XAML
No Comments

I am back from Stockholm and the DevSum conference! It was a great trip, what a beautiful city and lovely people! It was great to be there with so many friends from our beautiful community, and especially my colleague and friend Rene Schulte.

On Thursday, I started by helping my good friend Tim Huckaby with his keynote. My role was very limited, just monitoring the live stream coming from Tim’s HoloLens. Tim is a great speaker and his keynote was very interesting and funny. So nice to see him! Later, Rene did a talk about HoloLens 3D development. Always a great pleasure to see Rene show how to use Unity and build 3D apps!

image6

On Friday, it was my turn to speak. I have a Windows 10 Universal session and I decided to spice it up with a few demos of new platforms. It was a bit scary because there were quite a few moving pieces, and everything had to play together perfectly. And it almost did! The only thing I didn’t think about is that the Continuum dock is “protected” with HDCP. That means that you cannot connect the Dock to a projector. Such an annoying (and useless) feature! Thankfully, the conference center where DevSum took place had awesome technicians, and one of them saved my day by connecting an HDMI-to-VGA adapter which circumvented the issue.

The talk was quite beefy: We defined what a Universal app is, then we talked about Adaptive UI. We discussed the Centennial and Islandwood bridges before talking about Continuum and HoloLens. The final demo saw me switch my presentation to my Windows 10 mobile phone (950XL), show some slides in Powerpoint, then demo some Universal apps on this platform. Finally I started the HoloLens application on my phone, in Continuum mode. Since this is also a Universal app, it adapted to the big screen beautifully and I could stream what I was seeing through my HoloLens. I demonstrated how universal applications run on the holographic platform, including our own apps. It’s just as simple as deploying them to the HoloLens!

image4

We definitely live exciting times, and it’s really great to be working on these new platforms. You can find the slides and sample code for this talk on my website. The session was recorded, and I will tweet when the recording is available for your viewing please, so stay tuned to my Twitter feed. Thanks to everyone who came to see this session. I really hope it was informative and useful to you!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Build keynote (day 2) Part 4

Build, Windows 10
No Comments

 

Qi Lu (Office 365)

  • Reinventing productivity
  • Largest user base (1.2 billion users!)
  • 3 billions minutes of Skype calls daily!
  • Connect to MS Office services
    • Unified API and SDKs
    • Single sign on (Azure)
    • Real time data
    • Intelligence
  • Microsoft Graph demo
  • OneDrive file picker integrate in DocuSign, allows to select files from OneDrive directly
  • Recipient selector can select users based on topics etc, even mistyped names
  • Shows custom integration of add-ins in Office
  • Starbucks CTO Gerri Martin-Flickinger
    • Shows integration of gift cards into Outlook
  • Conversations as a platform
    • Human language as extensible UI
    • Ubiquitous
    • WeChat in China
  • Announces general availability of Office 365 group connectors
    • Allows to connect services into the group conversation
  • Skype Web SDK integrates Skype within a website
  • Visit dev.office.com to start building
  • Incredible innovation

Steven Guggenheimer, John Shewchuk

  • Muzik demo
    • Programmable buttons
  • Project Murphy
  • Spotify video
  • Shows some additional UWP samles
  • Vuforia demo (VR middleware), turns 2D images into 3D meshes
  • Students, Imagine Cup
    • Group of 8th graders on stage
    • Their experiment goes in space on May 31st
    • Built with Lego and Microsoft!
GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Build keynote (day 2) Part 3

Build, Windows 10
No Comments

 

Back to Scott

  • Service Fabric
    • Age of Ascent, massive multiplayer game

Scott Hanselman

  • Service Fabric demo
  • Demos the Age of Ascent game
    • Huge number of transactions
    • Auto scale
    • Shows deploying to production while the game is playing
    • Game can self heal after a bad upgrade / coding error. Health monitor is looking for flaws and auto correcting them

Back to Scott

  • Azure Service Fabric is generally available today
  • Data + Intelligence
    • New services such as speech, vision recognition etc
    • Integrates in any app
    • AccuWeather video, runs on Azure
  • DocumentDB
    • Global Databases
    • Replicate data for multi region
    • Low latency, high consistency
    • Protocol support for MongoDB (can use MongoDB tools etc)
  • The Walking Dead game demo, runs on Azure
    • DocumentDB
  • Power BI Embedded
    • Pay only for what you use
    • In app data visualization
    • Milliman demo
GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Build keynote (day 2) Part 2

Build, Windows 10
No Comments

 

Scott Guthrie

  • Good to see the Gu on stage for more goodness!!
  • More regions for Azure than Google and AWS combined
  • Huge datacenters
  • Fast adoption of Azure at the moment
  • Enterprises are not an afterthought but a key point
  • Ready for enterprise, including security, privacy, certifications, etc
  • License to operate on mainland China
  • > 85% or Fortune 500 companies use Microsoft cloud
  • MS was always centered on developers
  • Choose to use Azure for Infrastructure only, or high level set of services
  • Lots of startups and small firms too

Web and Mobile

  • Xamarin
    • Acquired by Microsoft
    • More than 1.3 millions users
    • Loved by developers, trusted by enterprises
    • Nice customer video

Miguel de Icaza

  • Xamarin is very excited to join Microsoft
  • iOS emulator remoted into Windows so you can use touch in the emulator!
  • Android emulator on Windows and Xamarin inspector, allows you to run code on the fly, edit it while running, code completion etc
  • Can even run documents with text in between, for example for samples etc

Back to Scott

  • Xamarin will be FREE starting today
    • even for the free Visual Studio community edition
  • Xamarin will be open sourced and part of the .NET foundation
  • HockeyApp demo
  • Xamarin test cloud demo
  • BMW on stage
    • Automated driving, digital services
    • Amazing integration of intelligence, detecting obstacles etc
    • Build on Azure, open mobility cloud
  • Schneider Electric
    • Created smart devices for years
    • Logical step to add IOT
    • Azure IOT suite
  • Can integrate IOT business logic in azure in different ways
  • New Azure service:
    • Azure Functions
    • Serverless compute
    • Trigger on events + external servuces
    • C#, Node.js code
    • Open source runtime

Cameron Skinner (IOT)

  • Cool IOT demo, when a temperature sensor goes under 20 degrees, sends a message to his shirt using Azure Functions

 

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Build keynote (day 2) Part 1

Build, Windows 10
No Comments

Here we are again! Another keynote and as far as I heard you don’t want to miss it!

Yesterday was quite the whirlwind of meetings, events, parties and a whole lot of excitement. My feet are killing me, I didn’t sleep much but I am happy about everything. One really exciting event for my colleague Rene and I was the HoloLens presentation that we gave in the so-called HoloLens hub. You can read more about our HoloLens development experience in Rene’s blog.

The glamorous life of a speaker (taken before our #HoloLens presentation /cc René

Posted by Laurent Bugnion on Wednesday, March 30, 2016

Another highlight of course was the meeting the Regional Directors were offered with Microsoft CEO Satya Nadella. It was a very good discussion, in an informal tone, a very relaxed session. It confirmed a lot of my opinions about Satya, and the impression that Microsoft is in good hands with him.

So this just happened, side meeting with the Microsoft Regional Directors and Satya Nadella #Build2016

Posted by Laurent Bugnion on Wednesday, March 30, 2016

Let’s get started!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook