1 / 46

Programming Microsoft Silverlight for Windows Embedded Using .NET

SESSION CODE: WEM309. Programming Microsoft Silverlight for Windows Embedded Using .NET. Andy Wigley Device Application Development MVP APPA Mundi Ltd. What We Will Cover. Introduction to Silverlight for Windows Embedded (SWE)

anka
Télécharger la présentation

Programming Microsoft Silverlight for Windows Embedded Using .NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SESSION CODE: WEM309 Programming Microsoft Silverlight for Windows Embedded Using .NET Andy Wigley Device Application Development MVP APPA Mundi Ltd

  2. What We Will Cover • Introduction to Silverlight for Windows Embedded (SWE) • Building a Native SWE App using the Silverlight for Windows Embedded Tools • Building a Managed App that has a SWE UI • Linking Native and Managed Code Using COM and P/Invoke Interop • Hosting Managed User Controls in a SWE GUI

  3. Introduction to Silverlight for Windows Embedded (SWE) • Silverlight for Windows Embedded is a native (C++ based) user interface development framework for Windows Embedded Compact • Silverlight 2 implementation shipped with Windows Embedded CE 6.0 R3 • Silverlight 3 XAML supported in Windows Embedded Compact 7 • Very different from other flavors of Silverlight: • No Managed API • No browser plug-in • Out of browser only

  4. XAML • XML • Declarative Markup • SWE in Windows Embedded Compact 7 supports Silverlight 3 syntax X A M L eXtensible Application Markup Language <Grid> <TextBlockFontSize="48" Text="Hello world" /> </Grid>

  5. Silverlight 3 XAML Features • Many built-in controls • Customisable styles and templates • Rich presentation capabilities • Solid, Gradient and Image Brushes • Opacity • Pixel effects such as blur and drop shadow • Animations • Change properties of controls over time • Movement, visibility, coloretc

  6. XAML Elements Map To Code • XAML declarative markup is just another way of instantiating objects and setting properties • In code-behind you can work directly on objects created in XAML • In .NET: <Grid x:Name="LayoutRoot" Background="Black"> <Button x:Name="Button1" Click="Button1_Click" Content="Click Me!" Width="100" Height="30"Background="AliceBlue"></Button> </Grid> • private void Button1_Click(objectsender, RoutedEventArgse) • { • // Turn screen background red • this.LayoutRoot.Background= new • SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0)); • }

  7. With The Native API, It’s (Kinda) The Same // Locate the button in the object tree IXRButtonPtrpButton; pVisualHost->GetRootElement(&pRootElement); FindName(pRootElement, L"Button1", IID_IAXButton, &pButton); // Add OnClick Event handler pButton->AddClickEventHandler(CreateDelegate(pEventHandler, &EventHandler::OnButtonClick)); … classEventHandler { public: HRESULT OnButtonClick(IAXDependencyObject* pSender, AXEventArgs* pArgs) { // Do something when the user clicks the button… } }

  8. Tools for Rapid SWE App Development • Windows Embedded Compact 7: • Windows Embedded Silverlight Tools (WEST) • Integrates into Visual Studio 2008 • Generates C++ application from an Expression Blend 3 project • Windows Embedded CE 6.0 R3: • MVP Valter Minute created XAML2CPP • Command-line Tool to generate boilerplate C++ code from XAML • See: http://geekswithblogs.net/WindowsEmbeddedCookbook/archive/2009/11/11/xaml2cpp.aspx C:\Projects\SWETest> xaml2cpp Page.xaml XAML2CPP version 1.0.2.0 C:\Projects\SWETest>

  9. Windows Embedded Silverlight Tools Walk-throughDesign UI with Expression Blend 3 • Use Expression Blend 3 to create your UI • Select the Silverlight for Windows Embedded Application New Project template • Remember to give all your controls a x:Name attribute • Hook up Click, Load and other events as required • Ignore C# generated code

  10. Windows Embedded Silverlight Tools Walk-throughCreate the C++ Project in Visual Studio 2008 • Use Visual Studio 2008 • Create a new Visual C++Smart Device Project • Target an SDK for a Windows Embedded Compact 7 target that has Silverlight support • Select the Silverlight for Windows Embedded Application template • Select the Expression Blend Silverlight for Windows Embedded Application project file

  11. Windows Embedded Silverlight Tools Walk-throughModify the tool generated code • Tools generate a functional Silverlight application • Silverlight UI initialization logic in class App • Class generated for each XAML page in the application: MainPage.xaml => MainPage.cpp • Creates event handler methods for all Click and other events defined in XAML • Hereafter, you can work on the XAML in Expression Blend, and the code in Visual Studio at the same time

  12. Understanding the Silverlight for Windows Embedded App • SWE apps must initialize the XamlRuntime API, and the XRApplication object and then create a visual host • This logic all in the App::Initialize method • The SWE app must then call IXRVisualHost.StartDialog to run the application • This logic contained in the App::Run method • To perform actions on a control: • First locate it in the XAML object tree using the FindName method • Use IXRtypePtr smart pointer objects to store references to controls • Create a delegate for click event handlers and add to the control • All this logic generated for you in the code generated for the XAML page

  13. Startup Logic in the Native SWE App // ========================================================================== // WinMain – Application control logic for the native SWE app // ========================================================================== INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hInstPrev*/, LPWSTR /*lpCmdLine*/, int/*nShowCmd*/) { App AppInstance; HRESULT hr = AppInstance.Initialize(hInstance); if(SUCCEEDED(hr)) { hr = AppInstance.Run(); } returnAppInstance.GetWinMainResultCode(); }

  14. Hooking Up Event Handlers in the Native SWE App HRESULT MainPage::OnLoaded(__in IXRDependencyObject* pRoot) { UNREFERENCED_PARAMETER(pRoot); HRESULT hr = InitializeComponent(); // Add calls to FindName or Add___EventHandler() methods after this comment. if (m_pMyButton) { m_pMyButton->AddClickEventHandler(CreateDelegate(this, &MainPage::OnButtonClick)); } returnhr; } // OnLoaded

  15. Event Handler Methods in the Native SWE App // =========================================================================== // OnButtonClick // Description: Event handler implementation // // Parameters: pSender - The dependency object that raised the click event. // pArgs - Event specific arguments. // =========================================================================== HRESULT MainPage::OnButtonClick (IXRDependencyObject* pSender, XRMouseButtonEventArgs* pArgs) { HRESULT hr = E_NOTIMPL; if ((NULL == pSender) || (NULL == pArgs)) { hr = E_INVALIDARG; } returnhr; }

  16. Basic C++ Silverlight for Windows Embedded Programming Andy WigleyMVPAPPA Mundi Ltd DEMO

  17. Controlling SWE UI From Managed CodeFirst Steps Page • We can use the tool-generated code as the basis of a DLL that exports methods • A method to startup the XAML runtime • A callback function to communicate click events Click Me Textbox NativeDLL ManagedEXE Callback Startup

  18. Controlling SWE UI From Managed CodeCreating the native DLL • Start by creating a new C++ Smart Device Win32 project • Platform is your Windows Embedded Compact 7 SDK • Application type: DLL • Additional options: Export symbols • Call it: SWEnative • Add in all the files generated for the Silverlight app project • Alternatively, modify the Silverlight app project to create a dll, not an exe • Define the exported functions

  19. Export Functions to be called from Managed Code • Export required functions from the native DLL so that C# code can call them • Control function to run the XAML UI • Get/Set properties of controls • Control animations • Define SWENATIVE_EXPORTS in C++ Preprocessor Definitions in Project Properties • Declare the exported functions in SWENative.h: #ifdef SWENATIVE_EXPORTS #define SWENATIVE_API __declspec(dllexport) #else #define SWENATIVE_API __declspec(dllimport) #endif extern"C" SWENATIVE_API intRunXamlUI(); extern"C" SWENATIVE_API intGetControlText(LPWSTR lName, BSTR* pValue); extern"C" SWENATIVE_API intSetControlText(LPWSTR lName, LPWSTR lValue); extern"C" SWENATIVE_API intStartStoryboard(LPWSTR lName);

  20. Implement RunXamlUIStartup Function HINSTANCE hDll; static App *app; BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { caseDLL_PROCESS_ATTACH: hDll= (HINSTANCE)hModule; // Save the HINSTANCE handle of the dll break; caseDLL_THREAD_ATTACH: caseDLL_THREAD_DETACH: caseDLL_PROCESS_DETACH: break; } return TRUE; } extern"C" SWENATIVE_API intRunXamlUI() // Start the XAML UI { app = new App(); if (FAILED(app->Initialize(hDll))) return -1; // Call Initialize passing HINSTANCE of the dll if (FAILED(app->Run())) return -1; // Run doesn’t return until XAML UI exits return 0; }

  21. P/Invoke Exported Functions • Call exported functions from C# using P/Invoke • In C#, declare the function using the DllImport attribute • Call it in start-up logic of your managed app usingSystem.Runtime.InteropServices; namespaceManagedConsoleHost { classProgram { [DllImport("SWEnative.dll")] staticexternintRunXamlUI(); staticvoid Main(string[] args) { // Call the native method to run the UIRunXamlUI(); } } }

  22. Use Reverse P/Invoke To Communicate Click Events • Use Reverse P/Invoke to notify the managed client of control events such as OnClick, OnTextChanged etc • Define a typedef for the Callback function • Modify the RunXamlUI function to take a CALLBACK* parameter: • Modify App.h to add a CLICKCALLBACK member field • In RunXamlUI, store the pointer to the managed callback function: // This in SWEnative.h. Callback function prototype typedefvoid (CALLBACK *CLICKCALLBACK)(LPWSTR lParam); // Modify the RunXamlUI function to accept a parameter that specifies the callback extern"C" SWENATIVE_API intRunXamlUI(CLICKCALLBACK callback); extern"C" SWENATIVE_API intRunXamlUI(CLICKCALLBACK callback) { app = new App(); app->ClickCallback= callback; // Save the callback function for later …

  23. Calling Managed From Native • In the native event handler, call the Callback function: // This in MainPage.cpp: Declare event handler in UI class // ============================================================================ // OnButtonClick // // Description: Event handler implementation // Parameters: pSender - The dependency object that raised the click event. // pArgs - Event specific arguments. // ============================================================================ HRESULT MainPage::OnButtonClick (IXRDependencyObject* pSender, XRMouseButtonEventArgs* pArgs) { if(App::ClickCallback != NULL) { BSTR controlName; pSender->GetName(&controlName); // Call the callbackfunction, passing the name of the control raising the event App::ClickCallback((LPWSTR)controlName); } return S_OK; }

  24. Controlling SWE UI From Managed CodeProgram the managed client – 1 of 2 usingSystem.Runtime.InteropServices; namespaceSWEManagedHost { classProgram { [DllImport("SWEnative.dll")] staticexternintRunXamlUI(ClickCallBackDelegatecbdele); // Declare a delegate that matches the signature of the native CALLBACK publicdelegatevoidClickCallBackDelegate(StringBuildermsg); // Make this a static - to make sure // that the function pointer doesn't get garbage collected later on staticClickCallBackDelegatecbdele; // Continued…

  25. Controlling SWE UI From Managed CodeProgram the managed client – 2 of 2 // Continued… staticvoidMain(string[]args) { // Declare the delegate to the callback function cbdele= newClickCallBackDelegate(SilverlightClickEventHandler); // Call the native method to start up the UI, passing the delegate RunXamlUI(cbdele); } // Event handler executes when called from native privatevoidSilverlightClickEventHandler(StringBuildermsg) { MessageBox.Show("Click from Silverlight, control name: " + msg.ToString); } }

  26. Managed Silverlight for Windows Embedded Andy WigleyMVPAPPA Mundi Ltd DEMO

  27. Extending the Native DLL Capabilities • Starting up the XAML UI and handling event callbacks is just the beginning • For a full workable solution, we also need to: • Get and Set properties on controls • Start and Stop animations • Send gesture and mouse events • This could get complex! • Pass data • Change control visual states Page NativeDLL ManagedEXE Callback Click Me Get Start/Stop Textbox Set Initialize

  28. Application Architecture Model – View – Presenterdesign pattern • Silverlight encourages a design principle called ‘separation of concerns’ • Separation of presentation and content • The ‘presentation’ is the XAML-based UI – native code • The ‘content’ is everything else – managed code • This separation is even seen during app development • Designers create UI using Expression Blend and do not care about the program logic, apart from considering screen layout and transitions between ‘scenes’ or views • Developers program against the objects the designer defined in XAML View1 View2 Native Interface Managed Presenter logic Model - data

  29. Improving the ImplementationA COM object that allows fine-grained interaction with SWE objects • Created a COM object • Implements and defines a number of general purpose interfaces • Exposes as much of the SWE object methods and properties as possible • Wrapped in thin ‘wrapper’ methods that ease interaction with the SWE objects SLNative.lib ISLSimpleEventPublisher ISLShell ISLView IViewEventPublisher IGenericControl

  30. Improving the ImplementationAdded managed classes that are proxies for the SWE native objects Native Managed Button Application logic Control SLNative.lib TextBox View Others… App code View Framework

  31. Result: A Clean, Easy Managed Code API publicclassSampleApplicationView : SLBaseView { privateAppamundi.Windows.Controls.ButtonhelloButton = null; privateAppamundi.Windows.Controls.TextBoxtxtForename = null; privateAppamundi.Windows.Controls.TextBoxtxtSurname = null; publicSampleApplicationView(BaseShell shell):base(shell) { InitializeView(); // Create control objects that are proxies for those created in XAML helloButton = newAppamundi.Windows.Controls.Button("btnSayHello", this); txtForename = newAppamundi.Windows.Controls.TextBox("txtForename", this); txtSurname = newAppamundi.Windows.Controls.TextBox("txtSurname", this); helloButton.Click += newEventHandler( (s, a) => { txtForename.Text = "Vladimir"; // Set a control property MessageBox.Show("Hello " + txtForename.Text + " " + txtSurname.Text); }); } }

  32. Advanced Managed SWE Andy WigleyMVPAPPA Mundi Ltd DEMO

  33. Hosting Managed User Controls in a SWE UI • You can display managed Windows Forms user controls in a SWE XAML UI • Use the <xr:win32control> element in XAML to add a placeholder for the user control into the object tree • This element represents an IXRWin32Control object • To display the User Control, set the handle of the IXRWin32Control object to that of the User Control • This works with managed Windows Forms user controls • This has not been exhaustively tested!

  34. XAML With <xr:Win32Control> <UserControl xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml xmlns:xr="clr-namespace:EmbeddedXamlRuntime" x:Class="SimpleSLapp.Page" Width="640" Height="480" Background="#FFC42929"> <Grid x:Name="LayoutRoot"> <Button Height="99" Margin="176,44,216,0" VerticalAlignment="Top" Content="Button" Click="OnButtonClick" Background="#FF32A625" x:Name="MyButton"/> <TextBox Height="45" Margin="176,168,237,0" VerticalAlignment="Top" Text="TextBox" TextWrapping="Wrap" Background="#FFDACB19" x:Name="MyTextBox"/> <xr:Win32Control x:Name="WinFormTest" Height="200" Width="200" HorizontalAlignment="Left" Margin="203,0,237,23“ VerticalAlignment="Bottom" /> </Grid> </UserControl>

  35. Displaying a Win32 User Control in the Silverlight UI int ShowWin32Control(HWND win32Handle) { HRESULT retcode; IXRWin32ControlPtr pIWin32Ctl; // Find the placeholder IXRWin32Control control in the Silverlight object tree if(FAILED(retcode=root->FindName(L"WinFormTest",&pIWin32Ctl))) returnretcode; // Swap the handle of the found control with the one of the Win32 control pIWin32Ctl->SetHandle(win32Handle, false); // The Win32 control is now represented in the visual tree // and is integrated with the on-screen layout of peer controls in the window. // activate the visual host window and repaint the changed portion HWND HostWindow = NULL; GetVisualHost()->GetContainerHWND(&HostWindow); ShowWindow(HostWindow, SW_SHOW); UpdateWindow(HostWindow); return 0; }

  36. C# Code to Display the User Control publicpartialclassForm1 : Form { [DllImport("SWEnative.dll")] staticexternintShowWinFormControl(IntPtr handle); ... privatevoidSilverlightClickEventHandler(StringBuildermsg) { // Create an instance of the winforms user control we want to // plug into the Silverlight display UserControl1uc = newUserControl1(); uc.Visible = true; // Tell the Silverlight UI about it and it will display it ShowWinFormControl(uc.Handle); } }

  37. Displaying Managed User Controls Andy WigleyMVPAPPA Mundi Ltd DEMO

  38. Summary • Silverlight for Windows Embedded allows you to create beautiful, rich UI • Using careful design, you can use SWE in a managed application • Define UI in XAML using Expression Blend • For simple apps • Use the Windows Embedded Silverlight Tools to generate native code from XAML • Write a thin wrapper in native code to export an API that managed code can call to initialize the XAML UI • Use Reverse P/Invoke to provide callbacks for UI events • For complex apps • Create a managed UI framework by building on top of the simple mechanisms used for simple apps

  39. Required Slide Track PMs will supply the content for this slide, which will be inserted during the final scrub. Track Resources • http://www.WindowsEmbedded.com • http://msdn.microsoft.com/en-us/windowsembedded • http://social.msdn.microsoft.com/Forums/en-US/category/embeddedwindows/ • http://social.msdn.microsoft.com/Forums/en-US/category/windowsembeddedcompact • https://connect.microsoft.com/windowsembeddedce

  40. Required Slide Speakers, please list the Breakout Sessions, Interactive Sessions, Labs and Demo Stations that are related to your session. Related Content • Breakout Sessions • WEM201 | Discover Windows Embedded Standard 7 as Your Next Application Platform • WEM301 | Deploying Windows Embedded Standard 7 with Style • WEM302 | Explore the Multimedia Potential of Windows Embedded Standard 7 • WEM303 | Gamechanger: Using Microsoft Silverlight for Windows Embedded to Create an Amazing Embedded UI • WEM305 | How to Choose a Windows Embedded Operating System • WEM306 | Using the Sensor & Location API on Windows Embedded Standard 7 to Create Exciting Connected Applications • WEM307 | Windows Embedded Compact: New Tools and Developer Story • WEM308 | Windows Embedded Overview: Demos of the Latest and Upcoming Releases • WEM309 | Programming Microsoft Silverlight for Windows Embedded Using Microsoft .NET • Interactive Sessions • WEM01-INT | Build a Secure Device with Windows Embedded Standard 7 • WEM02-INT | Delivering Flexible Peripheral Support for Point of Sale • WEM03-INT | How Windows Embedded Solutions Help to Protect the Environment • WEM05-INT | What a Desktop Developer Needs to Know to Develop for Windows Embedded • WEM06-INT | Windows Embedded Compact Compete • WEM07-INT | Server Appliances with Windows Embedded Servers • WEM08-INT | Roundtable: Windows Embedded @ Tech·Ed 2011 - Tell Us What You Want to Learn

  41. Required Slide Speakers, please list the Breakout Sessions, Interactive Sessions, Labs and Demo Stations that are related to your session. Related Content • Hands-on Labs • WEM01-HOL | Build Your Own Embedded System • WEM04-HOL | Porting Third-Party Drivers into Image Configuration Editor • Product Demo Stations (all on Windows Embedded booth) • TLC-46 | Get Your Hands on Windows Embedded • TLC-47 | Powered by Windows Embedded POSReady – Touch Screen • TLC-48 | The Intel® Intelligent Digital Signage Proof of Concept • TLC-49 | Windows Embedded Automotive • TLC-50 | Windows Embedded Device Showcase

  42. Required Slide Resources Learning • Sessions On-Demand & Community • Microsoft Certification & Training Resources www.microsoft.com/teched www.microsoft.com/learning • Resources for IT Professionals • Resources for Developers • http://microsoft.com/technet • http://microsoft.com/msdn

  43. Required Slide Complete an evaluation on CommNet and enter to win!

  44. Sign up for Tech·Ed 2011 and save $500 starting June 8 – June 31st http://northamerica.msteched.com/registration You can also register at the North America 2011 kiosk located at registrationJoin us in Atlanta next year

  45. © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

  46. Required Slide

More Related