以下文章以 http://download.csdn.net/detail/91program/7588393 中的工程为基础,这也是我写此文章时一步一步建立的 Silverlight 工程。
1 使用 Microsoft Expression Blend 3 创建一个 Silverlight for Windows Embedded Application 工程,放一个按键控件在窗体上,命名按键然后保存。由于 Microsoft Expression Blend 3 现在只支持生成 C# 的代码,对我们没有什么用,所以我们只用其中的 XAML 文件。
2 VS2008 新建:智能设备->Win32 智能设备项目,选拔一个支持 Silverlight 的SDK。
3 文件 SilverlightHelloWorld.cpp 中,只保留如下代码,其它删除:
1 // SilverlightHelloWorld.cpp : 定义应用程序的入口点。 2 // 3 4 5 #include "stdafx.h" 6 #include "SilverlightHelloWorld.h" 7 8 9 10 11 int WINAPI WinMain(HINSTANCE hInstance, 12 HINSTANCE hPrevInstance, 13 LPTSTR lpCmdLine, 14 int nCmdShow) 15 { 16 return 0; 17 }
4 新增加 4 个空文件,内容后面补,分别是:
App.cpp App.h MainPage.cpp MainPage.h
5 增加文件 XRPack.rules,文件的内容如下:
<?xml version="1.0" encoding="utf-8"?> <VisualStudioToolFile Name="XRPack Tool" Version="8.00" > <Rules> <CustomBuildRule Name="XRPack Tool" DisplayName="XRPack Tool" CommandLine=""$(VSInstallDir)VC\VCWizards\WindowsEmbeddedSilverlightTools\XRPack.exe" "/Root=$(ProjectDir)" "/IntermediateFiles=$(OutDir)" "@$(InputPath)"" Outputs="$(InputName)Generated.h $(InputName)Generated.rc2" FileExtensions="*.xrpack" ExecutionDescription="Generating RC2 file." > <Properties> </Properties> </CustomBuildRule> </Rules> </VisualStudioToolFile>
6 将 XRPack.rules 增加到工程文件 SilverlightHelloWorld.vcproj 中,修改了两个地方,修改后的内容如下:
<?xml version="1.0" encoding="gb2312"?> <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="SilverlightHelloWorld" ProjectGUID="{6DDF8C53-109B-4FC3-90B2-DD270ACA3A2C}" RootNamespace="SilverlightHelloWorld" Keyword="Win32Proj" TargetFrameworkVersion="196613" > <Platforms> <Platform Name="HSW_T9_SDK (ARMv4I)" /> </Platforms> <ToolFiles> <ToolFile RelativePath=".\XRPack.rules" /> </ToolFiles> <Configurations> <Configuration Name="Debug|HSW_T9_SDK (ARMv4I)" OutputDirectory="$(PlatformName)\$(ConfigurationName)" IntermediateDirectory="$(PlatformName)\$(ConfigurationName)" ConfigurationType="1" CharacterSet="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="XRPack Tool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> ......
7 新增文件 SilverlightHelloWorld.xrpack,其内容如下:
# This file is used to generate the rc2 file and baml resources # Uncomment /C to force xrpack to perform a clean build every time # /C # Verbosity can be a value between 1 and 10 /Verbosity=3 /NoResourceCompile "/TargetRC=WinEmbeddedHelloWorldGenerated.rc2" "/TargetHeader=WinEmbeddedHelloWorldGenerated.h" "/Project=..\WinEmbeddedHelloWorld\WinEmbeddedHelloWorld.csproj"
8 修改 stdafx.h ,增加以下内容:
1 // Xaml Runtime Header Files 2 #include <XamlRuntime.h> 3 #include <XRDelegate.h> 4 #include <XRPtr.h> 5 #include <XRCustomControl.h> 6 7 8 // IUnknown 9 extern "C" const GUID __declspec(selectany)IID_IUnknown = __uuidof(IUnknown); 10 11 12 // Resource type for XAML files 13 #define RT_XAML L"XAML" 14 15 16 // Application headers 17 #include "App.h" 18 #include "resource.h"
9 将 SilverlightHelloWorld.xrpack 文件增加到工程中
这样才能自动生成 WinEmbeddedHelloWorldGenerated.rc2 和 WinEmbeddedHelloWorldGenerated.h 文件
10 WinMain() 函数的实现代码如下:
11 编译,是可以成功的,但还需要根据 XAML 文件的内容来修改 MailPage.cpp 和 MailPage.h。
MailPage.h
1 #pragma once 2 3 4 // <UserControl x:Class="SilverlightClock.MainPage"> 5 class __declspec(uuid("{1756acb7-63be-4a4b-97cf-edc048541e75}")) MainPage 6 : public XRCustomUserControlImpl<MainPage> 7 { 8 QI_IDENTITY_MAPPING(MainPage, XRCustomUserControlImpl) 9 10 11 public: 12 static HRESULT GetXamlSource(__in XRXamlSource* pXamlSource) 13 { 14 HRESULT hr = E_INVALIDARG; 15 16 17 if (pXamlSource) 18 { 19 pXamlSource->SetResource (App::GetHInstance(), IDR_SILVERLIGHTCLOCK_MAINPAGE); 20 hr = S_OK; 21 } 22 23 return hr; 24 } 25 26 27 static HRESULT Register() 28 { 29 return XRCustomUserControlImpl<MainPage>::Register (__uuidof(MainPage), L"MainPage", L"clr-namespace:SilverlightClock"); 30 } 31 32 33 #pragma region GeneratedCode 34 // ============================================================================ 35 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED CODE 36 // ============================================================================ 37 HRESULT OnLoaded(__in IXRDependencyObject* pRoot); 38 HRESULT InitializeComponent(); 39 40 41 IXRGridPtr m_pLayoutRoot; // Grid x:Name="LayoutRoot" ... 42 IXRButtonBasePtr m_MyBtn; 43 IXRDelegate<XRMouseButtonEventArgs> *m_clickDelegate; 44 // ============================================================================ 45 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED CODE 46 // ============================================================================ 47 #pragma endregion GeneratedCode 48 };
MailPage.cpp
1 #include "stdafx.h" 2 #include "SilverlightHelloGenerated.h" 3 #include "MainPage.h" 4 #include "App.h" 5 #include "resource.h" 6 7 8 #define TEST_BTN_CLICK_PROCESS 1 9 10 11 #if TEST_BTN_CLICK_PROCESS 12 class BtnEventHandler 13 { 14 public: 15 HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args) 16 { 17 MessageBox(NULL,TEXT("Click!"),TEXT("Silverlight for Hello World!!!"),MB_OK); 18 return S_OK; 19 } 20 }; 21 #endif 22 23 24 // ============================================================================ 25 // OnLoaded 26 // 27 // Description: Calls InitializeComponent to bind member variables to named 28 // elements, and attach event handlers specified in XAML 29 // 30 // Parameters: pRoot - The root dependency object. 31 // ============================================================================ 32 HRESULT MainPage::OnLoaded(__in IXRDependencyObject* pRoot) 33 { 34 UNREFERENCED_PARAMETER(pRoot); 35 36 37 HRESULT hr = InitializeComponent(); 38 39 40 return hr; 41 } // OnLoaded 42 43 44 #pragma region GeneratedCode 45 // ============================================================================ 46 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED CODE 47 // ============================================================================ 48 HRESULT MainPage::InitializeComponent() 49 { 50 HRESULT hr = E_FAIL; 51 m_clickDelegate = NULL; 52 53 54 FindName(L"LayoutRoot", &m_pLayoutRoot); 55 56 57 #if TEST_BTN_CLICK_PROCESS 58 { 59 HRESULT retCode = 0; 60 BtnEventHandler handler; 61 62 63 if(FAILED(retCode = FindName(TEXT("HelloWorldBtn"), &m_MyBtn))) 64 return -1; 65 /* 66 指向委托对象的指针并不是一个智能指针(smart pointer),我们需要显式释放它:clickDelegate->Release(); 67 现在未释放!!!可以仿 OnLoaded 中 AddLoadedEventHandler 的实现方式。 68 */ 69 if(FAILED(retCode = CreateDelegate(&handler,&BtnEventHandler::OnClick,&m_clickDelegate))) 70 return -1; 71 if(FAILED(retCode = m_MyBtn->AddClickEventHandler(m_clickDelegate))) 72 return -1; 73 } 74 #endif 75 76 77 if (m_pLayoutRoot && m_MyBtn) 78 { 79 hr = S_OK; 80 } 81 82 83 return hr; 84 } 85 // ============================================================================ 86 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED CODE 87 // ============================================================================ 88 #pragma endregion GeneratedCode
12 App.cpp 和 App.h 的代码如下:
App.h
1 #pragma once 2 3 4 #include <XamlRuntime.h> 5 6 7 // 8 // This function pointer type is used to declare a table of 9 // registration functions in App.cpp 10 // 11 typedef HRESULT (*PFN_XRCUC_REGISTER)(); 12 13 14 // 15 // This is the main application class. 16 // 17 class App 18 { 19 public: 20 21 22 // 23 // Intialize member variables that cannot fail initialization in the constructor. 24 // 25 App(): 26 m_bInitialized(FALSE), 27 m_nResult(0) 28 { 29 } 30 31 32 // 33 // Destructor 34 // 35 ~App() {} 36 37 38 // Intialize the XamlRuntime API, a VisualHost, and initialize the application 39 HRESULT Initialize(HINSTANCE hInstance); 40 41 42 // Create the VisualHost. 43 HRESULT CreateHost(XRWindowCreateParams* pCreateParams); 44 45 46 // Run the application until the message pump exits. 47 HRESULT Run(); 48 49 50 // Register the UserControls implemented in this module 51 HRESULT RegisterUserControls(); 52 53 54 // Get the host window creation parameters 55 HRESULT GetWindowParameters(XRWindowCreateParams* pWindowParameters); 56 57 58 // Get the result code to be returned from WinMain 59 int GetWinMainResultCode(); 60 61 62 // Set the result code to be returned from WinMain 63 void SetWinMainResultCode(int nResult); 64 65 66 // Get the application HINSTANCE 67 static HINSTANCE GetHInstance(); 68 69 70 // Exit the application 71 HRESULT Exit(); 72 73 74 // OnStartup is called after the visual host is created 75 // and before the message loop is entered 76 HRESULT OnStartup(); 77 78 79 // OnExit is called after the message pump is exited 80 // and before the visual host, and IXRApplication are destroyed. 81 HRESULT OnExit(); 82 83 84 // Register the resource dictionary for this application 85 HRESULT InitializeComponent(); 86 87 88 // Gets the visual host for this application 89 static HRESULT GetVisualHost(IXRVisualHost** ppHost); 90 91 92 // Gets IXRApplication for this class 93 static HRESULT GetApplication(IXRApplication ** ppApp); 94 95 96 private: 97 // Sets the visual host for this application 98 static void SetVisualHost(IXRVisualHost* pHost); 99 100 101 // Sets IXRApplication for this class 102 static void SetApplication(IXRVisualHost* pApp); 103 104 105 protected: 106 // member variables 107 BOOL m_bInitialized; // Initialization succeeded 108 int m_nResult; // WinMain result code 109 110 111 // static member variables 112 static HINSTANCE m_hInstance; // The HINSTANCE of this process 113 // 为指向运行 SilverLight 应用程序的单体对象,此对象用来加载管理分析 XAML 文件。 114 static IXRApplicationPtr m_pApplication; // IXRApplication for this process 115 // 指向 Windows(HWND) 容器对象对象树,以便在运行时用 C++ 或 XAML 创建的对象处理相应事件消息,并显示或隐藏其 XAML 或 C++ 类创建的窗口。 116 static IXRVisualHostPtr m_pVisualHost; // IXRVisualHost for this process 117 }; 118 119 120 121 122 // ============================================================================ 123 // Initialize 124 // 125 // Description: Intialize the XamlRuntime API, and the XRApplication and then 126 // create a visual host. 127 // 128 // Parameters: hInstance - The HINSTANCE from WinMain 129 // ============================================================================ 130 inline HRESULT App::Initialize(HINSTANCE hInstance) 131 { 132 HRESULT hr = E_FAIL; 133 134 135 // 创建主窗口并让 SE 管理它的内容 136 XRWindowCreateParams WindowParameters = {0}; 137 138 139 m_hInstance = hInstance; 140 // Public API exported from XamlRumtime.dll. Initialize the system. 141 BOOL m_bInitialized = XamlRuntimeInitialize(); 142 143 144 // Create IXRApplication instance 145 if (m_bInitialized) 146 { 147 // Public API exported from XR.dll. Obtain a reference to the XRApplication object singleton. 148 hr = GetXRApplicationInstance(&m_pApplication); 149 } 150 151 152 if (SUCCEEDED(hr)) 153 { 154 // Add this module for the XamlRuntime to use when automatically resolving Image Source URIs as presented in XAML. 155 hr = m_pApplication->AddResourceModule(m_hInstance); 156 } 157 158 159 if (SUCCEEDED(hr)) 160 { 161 hr = RegisterUserControls(); 162 } 163 164 165 if (SUCCEEDED(hr)) 166 { 167 hr = InitializeComponent(); 168 } 169 170 171 if (SUCCEEDED(hr)) 172 { 173 hr = GetWindowParameters(&WindowParameters); 174 } 175 176 177 if (SUCCEEDED(hr)) 178 { 179 hr = CreateHost(&WindowParameters); 180 } 181 182 183 if (SUCCEEDED(hr)) 184 { 185 hr = OnStartup(); 186 } 187 188 189 return hr; 190 } // Initialize 191 192 193 // ============================================================================ 194 // Run 195 // 196 // Description: Run the application until the message pump exits. 197 // ============================================================================ 198 inline HRESULT App::Run() 199 { 200 HRESULT hr = E_FAIL; 201 UINT uiExitCode = 0; 202 203 204 if (m_pVisualHost != NULL) 205 { 206 // save the exit code for WinMain 207 hr = m_pVisualHost->StartDialog(&uiExitCode); 208 SetWinMainResultCode(uiExitCode); 209 } 210 211 212 // Allow user to cleanup resources. 213 OnExit(); 214 215 216 // 217 // XamlRuntime interfaces must be released in the 218 // following order: IXRVisualHost, IXRApplication. 219 // After these interfaces are released the runtime 220 // can be uninitialized. 221 // 222 223 224 // First release IXRVisualHost 225 m_pVisualHost = NULL; 226 227 228 // Second release IXRApplication 229 m_pApplication = NULL; 230 231 232 // If XamlRuntime was initialized, uninitialize it 233 if (m_bInitialized) 234 { 235 m_bInitialized = FALSE; 236 XamlRuntimeUninitialize(); 237 } 238 239 240 m_hInstance=NULL; 241 242 243 return hr; 244 } // Run 245 246 247 248 249 // ============================================================================ 250 // GetWinMainResultCode 251 // 252 // Description: Get the result code to be returned from WinMain 253 // ============================================================================ 254 inline int App::GetWinMainResultCode() 255 { 256 return m_nResult; 257 } // GetWinMainResultCode 258 259 260 // ============================================================================ 261 // SetWinMainResultCode 262 // 263 // Description: Set the result code to be returned from WinMain 264 // 265 // Parameters: nResult - The result code to be returned from WinMain 266 // ============================================================================ 267 inline void App::SetWinMainResultCode(int nResult) 268 { 269 m_nResult = nResult; 270 } // SetWinMainResultCode 271 272 273 // ============================================================================ 274 // GetHInstance 275 // 276 // Description: Get the application HINSTANCE 277 // ============================================================================ 278 inline HINSTANCE App::GetHInstance() 279 { 280 return m_hInstance; 281 } // GetHInstance 282 283 284 // ============================================================================ 285 // Exit 286 // 287 // Description: Exit the application 288 // ============================================================================ 289 inline HRESULT App::Exit() 290 { 291 HRESULT hr = E_FAIL; 292 293 294 if (NULL != m_pVisualHost) 295 { 296 hr = m_pVisualHost->EndDialog(0); 297 } 298 299 300 return hr; 301 } // Exit 302 303 304 // ============================================================================ 305 // GetVisualHost 306 // 307 // Gets the visual host for this application 308 // ============================================================================ 309 inline HRESULT App::GetVisualHost(IXRVisualHost ** ppHost) 310 { 311 if (!ppHost) 312 return E_INVALIDARG; 313 314 315 if (m_pVisualHost) 316 { 317 *ppHost = m_pVisualHost; 318 (*ppHost)->AddRef(); 319 return S_OK; 320 } 321 322 323 return E_FAIL; 324 } 325 326 327 // ============================================================================ 328 // SetVisualHost 329 // 330 // Sets the visual host for this application 331 // ============================================================================ 332 inline void App::SetVisualHost(IXRVisualHost* pHost) 333 { 334 // Smart pointer automatically calls AddRef 335 m_pVisualHost = pHost; 336 } 337 338 339 // ============================================================================ 340 // GetApplication 341 // 342 // Gets IXRApplication for this class 343 // ============================================================================ 344 inline HRESULT App::GetApplication(IXRApplication ** ppApp) 345 { 346 HRESULT hr = E_FAIL; 347 348 349 if (!ppApp) 350 return E_INVALIDARG; 351 352 353 if (m_pApplication) 354 { 355 *ppApp = m_pApplication; 356 (*ppApp)->AddRef(); 357 hr = S_OK; 358 } 359 360 361 return hr; 362 } 363 364 365 // ============================================================================ 366 // SetApplication 367 // 368 // Sets IXRApplication for this class 369 // ============================================================================ 370 inline void App::SetApplication(IXRVisualHost* pApp) 371 { 372 // Smart pointer automatically calls AddRef 373 m_pApplication = pApp; 374 }
App.cpp
1 #include "stdafx.h" 2 #include "SilverlightHelloGenerated.h" 3 #include "App.h" 4 #include "MainPage.h" 5 6 7 // The MAX_LOADSTRING constant needs to be equal to or greater 8 // than the length of the string referenced by IDS_APP_TITLE 9 #define MAX_LOADSTRING 100 10 11 12 // ============================================================================ 13 // Static class member instantiation. 14 // ============================================================================ 15 HINSTANCE App::m_hInstance; // HINSTANCE of this process 16 IXRApplicationPtr App::m_pApplication; // IXRApplication for this process 17 IXRVisualHostPtr App::m_pVisualHost; // IXRVisualHost for this process 18 19 20 // ============================================================================ 21 // InitializeComponent 22 // 23 // Description: Load the Application resource dictionary if one exists. 24 // ============================================================================ 25 HRESULT App::InitializeComponent() 26 { 27 XRXamlSource appXaml(GetHInstance(), IDR_SILVERLIGHTCLOCK_APP); 28 HRESULT hr = m_pApplication->LoadResourceDictionary(&appXaml,NULL); 29 return hr; 30 } // InitializeComponent 31 32 33 // ============================================================================ 34 // GetWindowParameters 35 // 36 // Description: Set the window creation parameters for this application. 37 // 38 // Parameters: pWindowParameters - Window creation parameters. 39 // ============================================================================ 40 HRESULT App::GetWindowParameters(XRWindowCreateParams* pWindowParameters) 41 { 42 static WCHAR szTitle[MAX_LOADSTRING]; // title bar text 43 44 45 HRESULT hr = E_INVALIDARG; 46 if (pWindowParameters) 47 { 48 pWindowParameters->Style = WS_VISIBLE; 49 pWindowParameters->ExStyle = WS_EX_TOPMOST; 50 51 52 // Set the title bar text 53 LoadString(m_hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); 54 pWindowParameters->pTitle = szTitle; 55 56 57 // Set window position 58 pWindowParameters->Left = 0; 59 pWindowParameters->Top = 0; 60 61 62 // TODO: To specify a window size for the visual host set Width and Height 63 // If Width and Height are zero the Width and Height specified in the 64 // XAML are used 65 66 67 //pWindowParameters->Width = GetSystemMetrics(SM_CXSCREEN); 68 //pWindowParameters->Height = GetSystemMetrics(SM_CYSCREEN); 69 70 71 hr = S_OK; 72 } 73 return hr; 74 } // GetWindowParameters 75 76 77 // ============================================================================ 78 // OnStartup 79 // 80 // Description: OnStartup is called after the visual host is created. 81 // and before the message loop is entered. 82 // ============================================================================ 83 HRESULT App::OnStartup() 84 { 85 HRESULT hr = S_OK; 86 87 88 IXRFrameworkElementPtr pRoot; 89 90 91 hr = m_pVisualHost->GetRootElement(&pRoot); 92 if (SUCCEEDED(hr)) 93 { 94 // TODO: Add one time initialization code here. 95 } 96 97 98 return hr; 99 } // OnStartup 100 101 102 // ============================================================================ 103 // OnExit 104 // 105 // Description: OnExit is called after the message pump is exited 106 // and before the visual host, and IXRApplication are destroyed. 107 // ============================================================================ 108 HRESULT App::OnExit() 109 { 110 // TODO: Add one-time cleanup code here. 111 return S_OK; 112 } // OnExit 113 114 115 // ============================================================================ 116 // CreateHost 117 // 118 // Description: Create the visual host. 119 // 120 // Parameters: pCreateParams - The parameters used for creating the 121 // visual host's window 122 // ============================================================================ 123 HRESULT App::CreateHost(XRWindowCreateParams* pCreateParams) 124 { 125 XRPtr<IXRCustomUserControl> pControl; 126 HRESULT hr = E_FAIL; 127 128 129 hr = m_pApplication->CreateObject(__uuidof(MainPage),&pControl); 130 if (SUCCEEDED(hr)) 131 { 132 hr = m_pApplication->CreateHostFromElementTree(pControl, pCreateParams, &m_pVisualHost); 133 } 134 135 136 return hr; 137 } 138 139 140 #pragma region RegisterUserControls Generated Code 141 // ============================================================================ 142 // RegisterUserControls 143 // 144 // Description: Register all XRCustomUserControl implemenations here. 145 // 146 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED FUNCTION 147 // ============================================================================ 148 HRESULT App::RegisterUserControls() 149 { 150 HRESULT hr = S_OK; 151 152 153 static PFN_XRCUC_REGISTER pfn[] = 154 { 155 &MainPage::Register, 156 }; 157 158 159 for (int i=0; i<_countof(pfn) && SUCCEEDED(hr); i++) 160 { 161 hr = pfn[i](); 162 163 164 if (FAILED(hr)) 165 { 166 RETAILMSG(1,(L"RegisterUserControls failed.")); 167 } 168 169 170 } 171 172 return hr; 173 } // RegisterUserControls 174 175 176 // ============================================================================ 177 // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED FUNCTION 178 // ============================================================================ 179 #pragma endregion RegisterUserControls Generated Code
13 编译、运行,失败了!程序没有加载起来。一般来说,没有加载成功是因为 XMAL 解析失败,或资源没有加载成功。需要进一步分析是什么具体的原因?
调试代码发现,如下函数在加载资源时报错: hr = -2147023082 {找不到映像文件中指定的资源名。}
1 HRESULT App::InitializeComponent() 2 { 3 XRXamlSource appXaml(GetHInstance(), IDR_SILVERLIGHTCLOCK_APP); 4 HRESULT hr = m_pApplication->LoadResourceDictionary(&appXaml,NULL); 5 return hr; 6 } // InitializeComponent
解决方法:
将资源文件 SilverlightHelloWorld.rc 中的 SilverlightHelloWorld.rc2 替换成 SilverlightHelloGenerated.rc2,共两处。
14 编译、运行,可以看到想要的界面。点击按键,会弹出一个对话框。
OK,到此新建 WinCE 下 Silverlight 工程的整个过程算是结束了,是不是有些复杂?
呵呵...,个人的感觉也是,挺复杂的。